3

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) 
4
  • Not sure what is wrong here. What's the error there? Commented Nov 24, 2016 at 17:57
  • 2
    @AliGajani They want to exclude 0.00 Commented Nov 24, 2016 at 17:57
  • radius = round(random.uniform(0.01, 0.1), 2) Commented Nov 24, 2016 at 17:59
  • 2
    @Janukasamaranyake Note that using round() creates a bias, because 0.01 is less likely to occur than 0.02 Commented Nov 24, 2016 at 18:00

3 Answers 3

8

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for the help
@Hello You are welcome! Next time there's no need to thank; simply upvote and accept the answer
0
radius = round(random.uniform(0.005, 0.10499999999999), 2) print(radius) 

you also need to extend the range of the sampled values to make sure that the probability of selecting the edge numbers 0.01 and 0.1 is the same as that of any other number in the desired range. otherwise, they will be sampled with half of probability of other numbers. I assume that round function rounds up i.e. 0.105 would end up as 0.11 not 0.10.

Comments

-1

Try subtract random value from max value as uniform includes low, but excludes high then you will get values from 0 to max excluding low and including high:

radius = round(0.1-random.uniform(0, 0.1), 2) 

1 Comment

This still produces the same distribution, and still produces 0.00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.