-3

How would I go about generating a random float and then rounding that float to the nearest decimal point in Python 3.4?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
lt468
  • 81
  • 1
  • 7

2 Answers2

2

Method 1:

You need two things: The random module and the builtin function round().

First you need a random number. This is as easy as:

import random
a = random.random() 

This will produce a number between 0 and 1. Next use round() to round it:

b = round(a, 1) # Thanks to https://stackoverflow.com/users/364696/shadowranger for the suggestion 
print(b)

The second argument in round() specifies the number of decimal places it rounds to in this case 1 which means it rounds to 1 decimal place.

and your done.

Method 2:

The other way you can do this is to use random.randint() this will produce a whole number within a range that we can then divide by 10 to get it to one decimal place:

import random # get the random module
a = random.randint(1, 9) # Use the randint() function as described in the link above
b = a / 10 # Divide by 10 so it is to 1 decimal place.
print(b)

and your done

Xantium
  • 11,201
  • 10
  • 62
  • 89
  • 2
    You don't need to multiply or divide at all. `round` takes two arguments, where the second is the number of digits to round to, so you could just do `b = round(a, 1)`, which directly rounds to a single digit after the decimal in a single step. – ShadowRanger Jan 06 '18 at 00:53
  • @ShadowRanger Corrected – Xantium Jan 06 '18 at 01:03
1

Assuming you want a float between 0.0 and 1.0, you can do it with:

import random
print(int(random.random()*10) / 10.0)

(Note that the division is by 10.0 and not 10 to force the float operation)

Output:

0.2
0.6
0.8
...

Basj
  • 41,386
  • 99
  • 383
  • 673
  • 2
    Won't `int` always round off? – Amos Egel Jan 05 '18 at 23:21
  • 1
    Fixed now @Simon. – Basj Jan 05 '18 at 23:42
  • 3
    Notes: 1. The OP specified Python 3; `/ 10` will work just fine (because `/` is true division on Py3, not floor division). 2. This doesn't round to *nearest* decimal, it rounds towards zero (if you generated `0.99999`, `9.9999` would be truncated to `9`, then division would get you `0.9`, not the closer `1.0`). – ShadowRanger Jan 06 '18 at 00:50