tags:

views:

113

answers:

4

Possible Duplicate:
Math - mapping numbers

I have value "x" that can be from 0 to 127 and a value "y" that can be from -1000 to 0. I need to make that if x = 0 than y = -1000 and if x = 127 than y = 0... How can i make it?

+3  A: 

It sounds like you just want a linear equation (y = mx + b). In your case, this would be

y = x*(1000/127) - 1000
Niki Yoshiuchi
Depending on the language this might yield inaccurate results (if it takes the 1000 and 127 and does an integer divide). You might want to mention that.
Andrew Rollings
Works fine! Many thanks to you :D
FBSC
And this is why modern programming courses don't have anywhere near enough math components :) (grumble grumble). Or enough onions on your belt.
Andrew Rollings
@FBSC - you may want to check that... if you're using that directly, then the 1000/127 will evaluate to (int)7, whereas you want it to evaluate to about 7.87... See my answer for more information.
Andrew Rollings
@Andrew i don't actually need that accuracy, since y is an integer, but i changed it :) thanks
FBSC
A: 

linear interpolation...

slope = (0 - -1000) / (127 - 0) = (1000.0/127.0) y-intercept = 127

y = (1000.0/127.0) * x - 1000

of course this assumes x and y can take on "real" values and not just integers.

vicatcu
+1  A: 

y = (x-127) * (1000/127)

Jonathan Park
+1  A: 
y = x * (1000.0/127.0) - 1000.0

Make sure you use float values in your calculation otherwise you will get inaccurate answers.

EDIT: And if you're really picky about accuracy, then this is better still:

y = (int) (0.5 + (x * (1000.0/127.0) - 1000.0))

(which will do correct rounding).

Andrew Rollings