PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Random » Generate Random Float numbers in Python using random() and Uniform()

Generate Random Float numbers in Python using random() and Uniform()

Updated on: June 16, 2021 | 3 Comments

In this lesson, you will learn how to generate a random float number in Python using random() and uniform() functions of a random module.

Use the following functions to generate random float numbers in Python. We will see each one of them with examples.

FunctionDescription
random.random()Returns a random float number between 0 and 1
random.uniform(10.5, 75.5)Returns a random float number between a range
round(random.uniform(33.33, 66.66), 2)Returns a random float number up to 2 decimal places
random.SystemRandom().uniform(5, 10)Returns a secure random float number
numpy.random.uniform()Returns a random array of floats
functions to generate random float numbers

Also, See:

  • Python random data generation Exercise
  • Python random data generation Quiz

Table of contents

  • Generate a random float number between 0 to 1
  • random.uniform() to get a random float number within a range
    • Syntax
    • Example
    • Points to remember about uniform() function
  • Generate a random float number up to 2 decimal places
    • Get random decimal
  • Random float number with step
  • Generate a list of random floats between a range
    • Create a list of unique random float numbers
  • Difference between uniform() and random()
  • Generate a secure random float number
  • Use numpy.random to generate an array of random float numbers
    • Get random float number using a NumPy
    • Numpy to generate a random float number between range
    • Create an n-dimensional array of float numbers
  • Next steps

Generate a random float number between 0 to 1

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).

import random

x = random.random()
# Random float number
for i in range(3):
    print(random.random())

Output:

0.5089695129344164
0.07174329054775652
0.7576474741201431

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.

random.uniform() to get a random float number within a range

The random.uniform() function returns a random floating-point number between a given range in Python. For example, It can generate a random float number between 10 to 100 Or from 50.50 to 75.5.

Syntax

random.uniform(start, stop)

The random.uniform() function returns a random floating-point number N such that start <= N <= stop.

In simple words, uniform(10.5, 15.5) will generate any float number greater than or equal to 10.5 and less than or equal to 20.5.

Parameters

The uniform() function accepts two arguments, and both are compulsory. If you miss any of them, you will get a TypeError uniform() missing 1 required positional argument.

  • start: it is the star number in a float range. i.e., lower limit. The default value is 0 if not specified.
  • stop: It is the end/last number in a range. It is the upper limit.

Example

Let see how to use the random.uniform() function to get a random float number within a range.

import random

# Random float number between range 10.5 to 75.5
print(random.uniform(10.5, 75.5))
# Output 27.23469913175497

# between 10 and 100
print(random.uniform(10, 100))
# Output 81.77036292015993

Points to remember about uniform() function

The start value need not be smaller than the stop value.

  • If start <= stop, it generates a random float number that is greater than or equal to the start number and less than or equal to the stop number.
  • If stop <= start, it generates a random float number that is greater than or equal to the stop number and less than or equal to the start number.
  • For example, you can use random.uniform() to generate a random float number between 10 to 100 and from 100 to 10. Both are treated the same.
  • The step argument is not available in random.uniform()

Generate a random float number up to 2 decimal places

As you can see in the above examples, a random float number has more than ten decimal places. In many cases, we need a random float number with limited decimal digits after the decimal point.

Use the round() function inside the random.random() and random.uniform() function to limit float number precision to two decimal places.

import random

# Random float number with 2 decimal places
print(round(random.random(), 2))
# Output 0.21

print(round(random.uniform(33.33, 66.66), 2))
# Output 62.0

# With 1 decimal places
print(round(random.random(), 1))
# Output 0.3

print(round(random.uniform(33.33, 66.66), 1))
# Output 54.6

Get random decimal

The random.uniform() and random.random() only returns float number. To get a random decimal.Decimal instance, you need explicitly convert it into decimal.Decimal.

import random
import decimal

# random decimal
x = decimal.Decimal(str(random.uniform(100, 1000)))
print(x)
# Output 936.3682817788443

Random float number with step

Let’s see how to generate a random float number from a range() with a specific interval (The step value).

For example, If you want to get a random integer from a range(1, 100, 2) with an interval 2, you can do that easily using random.choice(range(1, 100, 2)). But as you know, range() doesn’t support the float numbers. In this case, we need to convert an integer to floats.

import random

# random float from 1 to 99.9
int_num = random.choice(range(10, 1000))
float_num = int_num/10
print(float_num)
# Output 81.2

Note: we used random.choice() to choose a single number from the range of float numbers.

Generate a list of random floats between a range

In this section, we will see how to generate multiple random float numbers. In this example, we will see how to create a list of 10 random floats within a range of 50.50 to 500.50.

import random

random_float_list = []
# Set a length of the list to 10
for i in range(0, 10):
    # any random float between 50.50 to 500.50
    # don't use round() if you need number as it is
    x = round(random.uniform(50.50, 500.50), 2)
    random_float_list.append(x)

print(random_float_list)
# Output [98.01, 454.48, 117.69, 51.44, 415.01, 455.52, 65.39, 385.07, 112.38, 434.1]

Note: In the above example, there is a chance to get duplicate float numbers in a list. let’s see how to generate a list of unique random floats.

Create a list of unique random float numbers

If you want to generate a list of unique random float numbers, you can do that easily using random.sample(range(1, 100), 10)).

The random sample() function never generates the duplicate. But as you know, range() doesn’t support the float numbers. But we have two workarounds to get the list of unique random float numbers. Let’s see those.

Option 1: Use a list of integers to generate floats.

import random

list_Size = 10
# random float from 1 to 99.9
integer_list = random.sample(range(10, 1000), list_Size)
float_list = [x/10 for x in integer_list]
print(float_list)
# Output [7.9, 84.6, 72.1, 92.9, 64.1, 2.8, 32.6, 36.9, 97.4, 64.4]

Note: we used the random.sample() to choose 10 numbers from a range of numbers.

Option 2: Avoid duplicates manually

import random

def get_float_list(start, stop, size):
    result = []
    unique_set = set()
    for i in range(size):
        x = round(random.uniform(start, stop),2)
        while x in unique_set:
            x = round(random.uniform(start, stop),2)
        unique_set.add(x)
        result.append(x)

    return result

print("List of unique random numbers between 100, 1000")
print(get_float_list(100, 1000, 10))

# Output [918.45, 544.86, 595.18, 830.98, 516.11, 531.88, 255.85, 727.47, 687.23, 558.28]

Difference between uniform() and random()

  • The random() function doesn’t take any parameters, while uniform() takes two parameters, i.e., start and stop.
  • The random() function generates a random float number between 0.0 to 1.0 but never returns the upper bound. I.e., It will never generate 1.0. On the other side, the uniform(start, stop) generates any random float number between the given start and stop number. Due to the rounding effect, it can return a stop number.

Generate a secure random float number

Above all examples are not cryptographically secure. The cryptographically secure random generator generates random numbers using synchronization methods to ensure that no two processes can obtain the same number at the same time. If you are producing random floats for a security-sensitive application, then you must use this approach.

Use the random.SystemRandom().random()  or random.SystemRandom().uniform() functions to generate a secure random float number in Python.

Example

import random

secure_random = random.SystemRandom()

randomfloat = secure_random.random()
print(randomfloat)
# output 0.800760229291861

randomfloat = secure_random.uniform(12.5, 77.5)
print(randomfloat)
# Output 35.0470859352744

Read More: Python secrets module.

Use numpy.random to generate an array of random float numbers

NumPy isn’t a part of a standard Python library. However, it has various functions to generate random data. You can install NumPy using pip install numpy. Let see how to use it to generate a random float number and create an array of random float numbers.

Get random float number using a NumPy

import numpy as np

random_float = np.random.randn()
print(random_float)
# Output 0.833280610141848

Numpy to generate a random float number between range

import numpy as np

random_float_number = np.random.uniform(49.5, 99.5)
print(random_float_number)
# Output 59.11713060647423

Create an n-dimensional array of float numbers

Use a numpy.random.rand() to create an n-dimensional array of float numbers and populate it with random samples from a uniform distribution over [0, 1).

import numpy

random_float_array = numpy.random.rand(2, 3)
# Random float array 2X3
print(random_float_array,"\n")

Output:

[[0.34344184 0.8833125  0.76322675]
 [0.17844326 0.7717775  0.86237081]]

Between any float range

Use a numpy.random.uniform() function to generate a random 2×2 array.

import numpy

#2X2 random float
random_float_array = numpy.random.uniform(75.5, 125.5, size=(2, 2))
print(random_float_array)

Output:

[[107.50697835 123.84889979]
[106.26566127 101.92179508]] 

Next steps

I want to hear from you. Do you know other alternative ways of generating random float numbers Python? Or I missed one of the usages of random.uniform()?. Either way, let me know by leaving a comment below.

Also, try to solve the following exercise and quiz to have a better understanding of working with random data in Python.

  • Python random data generation Exercise
  • Python random data generation Quiz

Filed Under: Python, Python Random

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python Random

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python Random
TweetF  sharein  shareP  Pin

  Python Random Data

  • Guide to Generate Random Data
  • Random randint() & randrange()
  • Random Choice
  • Random Sample
  • Weighted random choices
  • Random Seed
  • Random Shuffle
  • Get Random Float Numbers
  • Generate Random String
  • Generate Secure random data
  • Secrets to Secure random data
  • Random Data Generation Exercise
  • Random Data Generation Quiz

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com