简体   繁体   中英

re-scaling the values between given maximum and minimum, where max is positive and min is negative

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...

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM