Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number function python that includes 1?

Tags:

python

random

I am new to Python and am trying to create a program for a project- firstly, I need to generate a point between the numbers 0-1.0, including 0 and 1.0 ([0, 1.0]). I searched the python library for functions (https://docs.python.org/2/library/random.html) and I found this function:

random.random()

This will return the next random floating point number in the range [0.0, 1.0). This is a problem, since it does not include 1. Although the chances of actually generating a 1 are very slim anyway, it is still important because this is a scientific program that will be used in a larger data collection.

I also found this function:

rand.randint

This will return an integer, which is also a problem.

I researched on the website and previously asked questions and found that this function:

random.uniform(a, b)

will only return a number that is greater than or equal to a and less than b.

Does anyone know how to create a random function on python that will include [0, 1.0]?

Please correct me if I was mistaken on any of this information. Thank you.

*The random numbers represent the x value of a three dimensional point on a sphere.

like image 213
user3550811 Avatar asked Apr 19 '14 04:04

user3550811


People also ask

Does Python random random include 1?

Python Random random() MethodThe random() method returns a random floating number between 0 and 1.

Can random random () give 1?

A random number generator always returns a value between 0 and 1, but never equal to one or the other.

How do you generate a random number 1 10 in Python?

You can use randint(0,50) to generate a random number between 0 and 50. To generate random integers between 0 and 9, you can use the function randrange(min,max) . Change the parameters of randint() to generate a number between 1 and 10.

How do you generate a random integer 0 or 1 in Python?

The random() function allows us to generate random numbers between 0 and 1 (generates floating-point random numbers). It is a default random generator function. The uniform() function generates random numbers between specified ranges rather than 0 and 1 (generates floating-point random numbers).


1 Answers

Could you make do with something like this?

random.randint(0, 1000) / 1000.0

Or more formally:

precision = 3
randomNumber = random.randint(0, 10 ** precision) / float(10 ** precision)
like image 93
icedtrees Avatar answered Oct 07 '22 23:10

icedtrees