Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random numbers in a specific range

Tags:

python

How would I generate random numbers to 2 decimal places in the range (0, 0.1]. My code so far is generating numbers with two decimal places in the range [0, 0.1]:

radius = round(random.uniform(0, 0.1), 2)
like image 707
Hello Avatar asked Aug 15 '26 15:08

Hello


1 Answers

Perhaps the easiest way to solve your problem is to think in terms of integers, not floating-point numbers.

You basically want possible random numbers like 0.01, 0.02, 0.03, ..., 0.09, 0.10.

First you generate an integer between 1 to 10 inclusive, then you divide by 100.0 to get a floating-point number.

Here is the code:

x = random.randint(1, 10)
y = x / 100.0

Documentation: random.randint(a, b)

like image 166
Nayuki Avatar answered Aug 17 '26 05:08

Nayuki