0

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?

Community
  • 1
  • 1
FBSC
  • 191
  • 2
  • 9

4 Answers4

3

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
  • 16,883
  • 1
  • 35
  • 44
  • 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 Jun 09 '10 at 17:14
  • 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 Jun 09 '10 at 17:16
  • @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 Jun 09 '10 at 17:20
  • @Andrew i don't actually need that accuracy, since y is an integer, but i changed it :) thanks – FBSC Jun 09 '10 at 17:22
1

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

Jonathan Park
  • 775
  • 5
  • 12
1
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
  • 14,340
  • 7
  • 51
  • 50
0

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
  • 5,407
  • 7
  • 41
  • 65