Python Multiply Operator Occasionally Yields a Long Float

I have this code:

for i in range(number_of_data_items):
    number = random.randrange(min, max, step) * multiplier
    datalist.append(float(number))

but some random numbers have a long decimal value:

[0.91, 0.61, 0.67, 0.79, 0.23, 0.73, 0.16, 0.99, 0.5700000000000001, 0.58, 0.32, 0.28, 0.6900000000000001, 0.56, 0.46, 0.4, 0.5700000000000001, 0.19, 0.21, 0.48, 0.97, 0.61, 0.14, 0.79, 0.43, 0.76, 0.97, 0.91, 0.54, 0.22, 0.64, 0.76, 0.5700000000000001, 0.52, 0.44, 0.1, 0.34, 0.51, 0.17, 0.36, 0.16, 0.7000000000000001, 0.18, 0.91, 0.55, 0.22, 0.61, 0.85, 0.98, 0.42, 0.9, 0.38, 0.96, 0.24, 0.87, 0.5, 0.99, 0.9500000000000001, 0.42, 0.8, 0.77, 0.91, 0.87, 0.98, 0.86, 0.77, 0.11, 0.9, 0.5, 0.71, 0.88, 0.86, 0.46, 0.9, 0.84, 0.33, 0.73, 0.43, 0.11, 0.96, 0.63, 0.76, 0.65, 0.23, 0.73, 0.7000000000000001, 0.33, 0.42, 0.61, 0.76, 0.24, 0.41000000000000003, 0.91, 0.46, 0.21, 0.9, 0.16, 0.27, 0.42, 0.7000000000000001]

I know it is not the random() function because I get perfect integers if I remove * multiplier.
Is this a Python bug? How can I fix it?

1 Like

AFAIK, this is just a python bug/math error, like if you add 0.01 and 0.02.

2 Likes

I think you can refer to the official python documentation.

https://docs.python.org/3/tutorial/floatingpoint.html

Welcome to the world of computers where numerous are approximations :stuck_out_tongue:

does using round(number, 2) syntax help, it rounds to a certain place

Particularly this is not a python problem but a issue in the whole field related to how floating-point numbers are represented internally. There’s a good explanation here of why this happen:

One way to “fix” this is by rounding the result to the number of decimal places you want by using the round() function. A simple example:

for i in range(number_of_data_items):
    number = random.randrange(min, max, step) * multiplier
    datalist.append(round(float(number), 2)) # round to 2 decimal places
3 Likes

Why was this marked as the solution when i said the same exact thing to use the rounding function one post prior ;-;. kudos nonetheless…

Probably because OP found it more helpful, as they linked a video explaining why and showed how OP’s code would look after the fix

3 Likes

grumbles in acceptance

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.