0

I am trying to check if a randomly generated value is inside one of several ranges I have. Those ranges go from 0 to 1, and whenever I try to use arange it doesn't find it. I tried to transform all the values to integers as well in order to use range, but it keeps missing the number.

The purpose of this snippet is to find which range the random number belongs to, in order to know to know what capacity the tank would have. For example, if the random number is 0.70, then the tank would have a capacity of 100 lt.

The simplest version I've tried is the following:

import random
import numpy as np

tank_capacity = [20,30,50,75,100] 
pbb = [0.01,0.10,0.25,0.30,0.25] 
pbb_acum = [0,0.10,0.35,0.65,0.90]

dict_pbb_acum = dict(zip(tank_capacity,pbb_acum))

combinations = [tank_capacity[i: i + 2] for i in range(len(tank_capacity)-1)]

n = random.random()
print(n)

if n >= 0.9:
    print("found")
else:
    for item in combinations:
        if n in np.arange(dict_pbb_acum[item[0]], dict_pbb_acum[item[1]],0.01):
            print("found")
        else:
            print("not found")

Thanks in advance!

  • This may be due to the nature of floating point numbers, could you simply check if the number is within the range directly? – AMC Jan 16 '20 at 21:19

1 Answers1

0

It's not clear what you're trying to do, but from the looks of it maybe something like this:

import random
import numpy as np

tank_capacity = [20,30,50,75,100] 
pbb = [0.01,0.10,0.25,0.30,0.25] 
pbb_acum = [0,0.10,0.35,0.65,0.90]

n = random.random()
if n > .9:
    print('pbb_accum of {} requires a tank capacity of {}'.format(n,tank_capacity[-1]))
else:
    for i, pa in enumerate(pbb_acum):
        if n < pa:
            print('pbb_accum of {} requires a tank capacity of {}'.format(n,tank_capacity[i]))
            break
Chris
  • 15,819
  • 3
  • 24
  • 37