-3

I want to generate random number between 0 and 1 in python code but only get 2 numbers after sign . Example:

 0.22 
 0.25
 0.9

I have searched many sources but have not found the solution. Can you help me?

  • What kind of radom generator function are you using? I am curious as to why you get only two decimal precision. – eroot163pi Aug 09 '21 at 07:58
  • 2
    @eroot163pi: the OP is trying to obtain this effect. –  Aug 09 '21 at 07:59
  • The question is incomplete, because you don't state in which exact range you want these random numbers (and we have to guess that you want them uniform, don't we ?). –  Aug 09 '21 at 08:00
  • 1
    It is a pity that the question was closed as already having answers. Because the rounding strategy is not the correct one, as it introduces a bias, and there is no place to discuss this now. –  Aug 09 '21 at 08:03
  • @yves i agree with you – eroot163pi Aug 09 '21 at 08:06
  • 1
    @december try to generate random integers from 0 to 99 using random.randint and divide by 100. This should give you floats upto 2 decimal without bias. I think....also i wish question is reopened to discussion – eroot163pi Aug 09 '21 at 08:10
  • 1
    @eroot163pi: you can vote for reopening. –  Aug 09 '21 at 09:11
  • @DecemberB: Should `0.0` be a possible output? What about `1.0`? What distribution of output values do you want: all output values equally likely? Note that the accepted `round(x, 2)` solution does not produce all values with equal likelihood: `0.0` and `1.0` are roughly half as likely to occur as any other value. – Mark Dickinson Aug 10 '21 at 13:42

3 Answers3

2

Want this?

import random
round(random.random(), 2)
Atralupus
  • 131
  • 1
  • 7
1

You can use the format method in python if you want EXACTLY 2 digits after the decimal point (for example if you want 0.90):

import random

x = random.random()
print("{:.2f}".format(x))

or if you are fine with numbers like 0.9:

import random

x = random.random()
print(round(x,2))
Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14
1

Try this print(round(random.random(), 2))

Kais
  • 67
  • 1
  • 9