Thursday, August 11, 2022

[FIXED] How to generate a random number to 2dp

Issue

I am trying to work on a random number generator which produces a random number which is to 2dp regardless of whether it needs to be. eg. 2.10 is 2.10 not 2.1, 3 = 3.00

import random

temp_var_4_int = random.randint(2,5) + round(random.random(),2)

print (temp_var_4_int)

It should randomize a number between 2 and 5 and then add a decimal to it which is rounded to 2 decimal places but I keep getting answers such as:

1.2700000000000002 instead of 1.27

I'm not sure why it's throwing this anomaly at me.


Solution

assuming you want your numbers in [0, 10] you could just do this:

from random import uniform

r = round(uniform(0, 10), 2)
print(f"{r:3.2f}")

if r = 2.1 the format string will represent it as "2.10"; but for all mathematical purposes the trailing zero has no effect.



Answered By - hiro protagonist
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.