Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate a floating point random number with two precision in python

Tags:

python

random

I want to generate a floating point random number with two precision. For example:2.54 How to change the uniform(a,b) in python. Thanks

like image 930
user3356423 Avatar asked May 25 '17 04:05

user3356423


People also ask

How do you print a float number up to 2 decimal places in Python?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.

How do you get a random floating point number in Python?

Use a random. random() function of a random module to generate a random float number uniformly in the semi-open range [0.0, 1.0) . Note: A random() function can only provide float numbers between 0.1. to 1.0. Us uniform() method to generate a random float number between any two numbers.

How do you get a float number up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


2 Answers

You can use round function with uniform function to limit float number to two decimal places.

Example:

 round(random.uniform(1.5, 1.9),2)
 Out[]: 1.62

 round(random.uniform(1.5, 1.9),3)
 Out[]: 1.885
like image 180
Sayali Sonawane Avatar answered Oct 17 '22 02:10

Sayali Sonawane


If you want to generate a random number between two numbers, with a specific amount of decimals, here is a way:

import random

greaterThan = float(1)
lessThan = float(4)
digits = int(2)

rounded_number = round(random.uniform(greaterThan, lessThan), digits)

in this case, your random number will be between 1 and 4, with two digits

like image 44
A Monad is a Monoid Avatar answered Oct 17 '22 01:10

A Monad is a Monoid