简体   繁体   中英

Convert the number to a fraction of specified range

So Im looking for some smart way to convert any number into a fraction. I need to achieve this:

0.0001 >= my_number >= 0.00001

the problem is that my_number may come as:

194619.98341

as well as:

0.00231134

(examples) so it is possibly any number greater than 0. Im struggling to create a function which will convert it so it belongs to the specified range.

If you have a list of numbers and you want them all to be included in this specified range, what you can do is:

def scale(numbers, low_bound, high_bound):
    return [(x - min(numbers)) / (max(numbers) - min(numbers)) * (high_bound - low_bound) + low_bound for x in numbers]

Now, if you it:

list = [1209.76671, 0.9831, 0.000009873, 123]
scale(list, 0.00001, 0.0001)

# which gives:
# [0.0001, 1.0073136507576801e-05, 1e-05, 1.9150523907020985e-05]

Note that this will always set the minimum of the list of numbers to 0.00001 and always set the maximum to 0.0001.

Now, I don't know if this answers your question so please tell me if I'm mistaken in interpreting your question...

turns out it was not that hard:

if x > 0.00001:
    while not 0.0001 >= x >= 0.00001:
        x = x / 10
else:
    while not 0.0001 >= x >= 0.00001:
        x = x * 10

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