Generate a random double between specific points in Python

Generate a random double between specific points in Python

To generate a random double (floating-point number) between specific points in Python, you can use the uniform function from the random module. This function allows you to specify the lower and upper bounds for the random number.

Here’s how you can do it:

import random

# Define the interval [a, b]
a = 1.5
b = 10.5

# Generate a random double within the interval [a, b]
random_double = random.uniform(a, b)
print(f"Random Double: {random_double}")

In this example, random.uniform(a, b) generates a random floating-point number between a and b, inclusive of both endpoints.

Example with Multiple Random Doubles

If you want to generate multiple random doubles within a specific interval, you can use a loop:

import random

# Define the interval [a, b]
a = 1.5
b = 10.5

# Number of random doubles to generate
num_doubles = 5

# Generate and print multiple random doubles
for _ in range(num_doubles):
    random_double = random.uniform(a, b)
    print(f"Random Double: {random_double}")

This script generates and prints five random doubles within the interval [1.5, 10.5]. Adjust the values of a, b, and num_doubles as needed.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top