python - range-like function for floats -


i wanted use built-in range function floats, apparently doesn't work , quick research, understood there isn't built in option , i'll need code own function this. did:

def fltrange(mini, maxi, step): lst = [] while mini < maxi:     lst.append(mini)     mini += step return lst  rang = fltrange(-20.0, 20.1, 0.1)  print(rang)  input() 

but get: result

the step should 0.1000000..., instead it's (sometimes changes) 0.100000000000001.

thanks in advance.

fun fact: 1/10 can't represented floating point numbers. closest can 0.1000000000000000055511151231257827021181583404541015625. rightmost digits left out when print them, they're still there. explains accumulation of errors continually add more 0.1s sum.

you can eliminate some inaccuracy (but not of it) using multiplication approach instead of cumulative sum:

def fltrange(mini, maxi, step):     lst = []     width = maxi - mini     num_steps = int(width/step)     in range(num_steps):         lst.append(mini + i*step)     return lst rang = fltrange(-20.0, 20.1, 0.1) print(rang) 

result (newlines added me clarity):

[-20.0, -19.9, -19.8, -19.7, -19.6, -19.5, -19.4, -19.3, -19.2, -19.1,  -19.0, -18.9, -18.8, -18.7, -18.6, -18.5, -18.4, -18.3, -18.2, -18.1,  -18.0, -17.9, -17.8, -17.7, -17.6, -17.5, -17.4, -17.3, -17.2, -17.1,  -17.0, -16.9, -16.8, -16.7, -16.6, -16.5, -16.4, -16.3, -16.2, -16.1,  -16.0, -15.899999999999999, -15.8, -15.7, -15.6, -15.5, -15.399999999999999, -15.3, -15.2, -15.1, -15.0, ... 19.1, 19.200000000000003, 19.300000000000004, 19.400000000000006, 19.5, 19.6, 19.700000000000003, 19.800000000000004, 19.900000000000006, 20.0] 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -