-2

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.

Sayse
  • 42,633
  • 14
  • 77
  • 146
  • The [fractions](https://docs.python.org/3/library/fractions.html) module exists, and while it will "convert any number into a fraction", I'm not sure what you're asking so I'm not sure how appropriate it is for what you're trying to do. But it may be worth looking in to. – jedwards Nov 04 '19 at 15:09
  • Possible duplicate of [Convert a number range to another range, maintaining ratio](https://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio) – rivamarco Nov 04 '19 at 15:19

2 Answers2

1

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

bglbrt
  • 2,018
  • 8
  • 21
0

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