杰瑞科技汇

Python random如何生成double类型随机数?

Of course! In Python, generating a random floating-point number (a "double" in many programming languages) is a common task. The primary tool for this is the random module.

Python random如何生成double类型随机数?-图1
(图片来源网络,侵删)

Here’s a complete guide, from the basics to more advanced use cases.

The Quick and Simple Answer: random.random()

This is the most common and straightforward way to generate a random float between 0.0 and 1.0 (including 0.0, but not including 1.0).

import random
# Generate a random float between 0.0 and 1.0
random_float = random.random()
print(f"A random float: {random_float}")
# Example output: A random float: 0.8765432098765432

Generating a Random Double in a Specific Range

Often, you need a random number within a custom range, like from 10.0 to 20.0. For this, you use random.uniform(a, b).

random.uniform(a, b) returns a random float N such that a <= N <= b if a <= b, or b <= N <= a if b < a.

Python random如何生成double类型随机数?-图2
(图片来源网络,侵删)

Example: Between 10.0 and 20.0

import random
# Generate a random float between 10.0 and 20.0 (inclusive of both ends)
random_in_range = random.uniform(10.0, 20.0)
print(f"A random float between 10.0 and 20.0: {random_in_range}")
# Example output: A random float between 10.0 and 20.0: 15.43210987654321

Example: Between a Negative and Positive Number

The function handles negative ranges seamlessly.

import random
# Generate a random float between -5.0 and 5.0
random_neg_pos = random.uniform(-5.0, 5.0)
print(f"A random float between -5.0 and 5.0: {random_neg_pos}")
# Example output: A random float between -5.0 and 5.0: -2.1098765432109875

Seeding the Random Number Generator (For Reproducibility)

Computers generate "random" numbers using a pseudo-random number generator (PRNG). This means the sequence is determined by an initial value called a "seed". If you use the same seed, you will get the exact same sequence of "random" numbers every time. This is crucial for testing, simulations, and debugging.

You can set the seed using random.seed().

import random
# Set the seed to a specific number (e.g., 42)
random.seed(42)
print("First run with seed 42:")
print(f"random.random(): {random.random()}") # Output: 0.6394267984578837
print(f"random.uniform(1, 10): {random.uniform(1, 10)}") # Output: 1.0226259553457507
print("\nResetting the seed to 42:")
random.seed(42) # Reset the seed
print("Second run with seed 42:")
print(f"random.random(): {random.random()}") # Output: 0.6394267984578837 (Same as before!)
print(f"random.uniform(1, 10): {random.uniform(1, 10)}") # Output: 1.0226259553457507 (Same as before!)

Other Useful random Module Functions

While random() and uniform() are the most direct ways to get a random double, the random module has other functions that are often useful.

random.randrange(start, stop, step)

This function is like the built-in range(), but it returns a random integer from the sequence. It's useful if you want to generate a random integer and then convert it to a float.

import random
# Get a random integer between 1 and 10 (inclusive of 1, exclusive of 10)
random_int = random.randrange(1, 10)
random_float_from_int = float(random_int)
print(f"Random integer: {random_int}")
print(f"Converted to float: {random_float_from_int}")

random.choice(sequence)

This picks a random element from a non-empty sequence (like a list, tuple, or string). It's useful if you have a predefined set of floats.

import random
# A list of predefined floating-point numbers
float_options = [3.14, 2.718, 1.618, 9.81]
# Choose one at random
selected_float = random.choice(float_options)
print(f"Randomly chosen float: {selected_float}")
# Example output: Randomly chosen float: 2.718

High-Quality Random Numbers: The secrets Module

For security-sensitive applications like generating API keys, password reset tokens, or security tokens, you should not use the random module. It is designed for modeling and simulation, not for cryptography.

Instead, use the secrets module, which is specifically designed for generating cryptographically strong random numbers.

secrets.choice() is the most common function, which works on a sequence. To get a random float in a specific range, you can combine it with random.uniform by setting the underlying generator.

import secrets
import random
# Generate a secure random float in the range [0.0, 1.0)
# This is the recommended way for security-sensitive applications.
secure_random_float = secrets.SystemRandom().random()
print(f"A cryptographically secure random float: {secure_random_float}")
# Generate a secure random float in a custom range [min, max]
min_val = 100.0
max_val = 200.0
secure_uniform_float = secrets.SystemRandom().uniform(min_val, max_val)
print(f"A secure random float between {min_val} and {max_val}: {secure_uniform_float}")

Summary: Which Function to Use?

Your Goal Recommended Function Module Notes
Get a random float between 0.0 and 1.0 random.random() random The most common and basic function.
Get a random float in a custom range [a, b] random.uniform(a, b) random The standard way for custom ranges.
Generate reproducible "random" numbers random.seed(some_number) random Essential for testing and simulations.
Pick a random float from a predefined list random.choice(my_list) random Use when your options are already in a sequence.
Generate a secure random number (for security) secrets.SystemRandom().random() or .uniform() secrets Always use this for passwords, tokens, or any security-critical data.
分享:
扫描分享到社交APP
上一篇
下一篇