How to normalize a list of positive and negative decimal number to a specific range

16,977

Solution 1

To get the range of input is very easy:

old_min = min(input)
old_range = max(input) - old_min

Here's the tricky part. You can multiply by the new range and divide by the old range, but that almost guarantees that the top bucket will only get one value in it. You need to expand your output range so that the top bucket is the same size as all the other buckets.

new_min = -5
new_range = 5 + 0.9999999999 - new_min
output = [floor((n - old_min) / old_range * new_range + new_min) for n in input]

Solution 2

>>> L = [-23.5, -12.7, -20.6, -11.3, -9.2, -4.5, 2, 8, 11, 15, 17, 21]
>>> normal = map(lambda x, r=float(L[-1] - L[0]): ((x - L[0]) / r)*10 - 5, L)
>>> normal
[-5.0, -2.5730337078651684, -4.348314606741574, -2.2584269662921352, -1.7865168539325844, -0.7303370786516856, 0.7303370786516847, 2.0786516853932575, 2.752808988764045, 3.6516853932584272, 4.101123595505618, 5.0]

Solution 3

original_vals = [-23.5, -12.7, -20.6, -11.3, -9.2, -4.5, 2, 8, 11, 15, 17, 21 ]

# get max absolute value
original_max = max([abs(val) for val in original_vals])

# normalize to desired range size
new_range_val = 5
normalized_vals = [float(val)/original_max * new_range_val for val in original_vals]
Share:
16,977

Related videos on Youtube

Surjya Narayana Padhi
Author by

Surjya Narayana Padhi

I feel passionate to work in computer vision. It like a magic to me. Giving machines intelligence is so cool thing. I like to work various projects which are cool. Like to learn any technology on my way to accomplish a cool project. Exploring data,applying machine learning techniques for prediction or statistical methods to get insights is so awesome. Creating nice visualization using python is so nice. My hobby : Reading recent science news, Astrology, music

Updated on September 29, 2022

Comments

  • Surjya Narayana Padhi
    Surjya Narayana Padhi over 1 year

    I have a list of decimal numbers as follows:

    [-23.5, -12.7, -20.6, -11.3, -9.2, -4.5, 2, 8, 11, 15, 17, 21]
    

    I need to normalize this list to fit into the range [-5,5].
    How can I do it in python?