Reputation: 2270
I want the re-scale an array of values (both positive and negative floating point values), so that the values lies between say -5 to +5 or say -3 to +2. How can I scale it down. Is there any specific formula for it. I tried searching, but did not found anything that can deal with negative min value.
Thanks in advance...
Upvotes: 3
Views: 11842
Reputation: 648
The easiest way to scale your data down is to determine the maximum value of your data (positive or negative) and use that to scale all the other data accordingly.
For example, if you had a maximum of 320 in your data
320 / 320 * 5 => 5
160 / 320 * 5 => 2.5
-160 / 320 * 5 => -2.5
So as a general equation
x / abs(maximum) * scale
Upvotes: 2
Reputation: 5252
You could use a linear interpolation/extrapolation formula to get the results you want.
Code:
def rescale(val, in_min, in_max, out_min, out_max):
return out_min + (val - in_min) * ((out_max - out_min) / (in_max - in_min))
print(rescale(4, 4, 20, 0, 100)) # => 0.0
print(rescale(12, 4, 20, 0, 100)) # => 50.0
print(rescale(20, 4, 20, 0, 100)) # => 100.0
print(rescale(0, 4, 20, 0, 100)) # => -25.0
Note that this code doesn't check your values against the min and max bounds supplied, hence it will extrapolate as in the last example. Modify it as you need.
Upvotes: 3
Reputation: 308868
Try something like this to map values onto a (0, 1) scale:
y = (x - xmin) / (xmax - xmin)
You can also use finite element shape functions:
y = h1*x1 + h2*x2
where
h1 = (z - 1)/2.0 for -1 <= z <= +1
h2 = (z + 1)/2.0 for -1 <= z <= +1
This maps your values onto a (-1, 1) scale.
Upvotes: 3