本文目录导读:

我来为你详细介绍Python生成随机浮点数的几种常用方法:
使用 random 模块
基础方法
import random
# 生成 [0.0, 1.0) 之间的随机浮点数
num1 = random.random()
print(f"random(): {num1}")
# 生成指定范围内随机浮点数 [a, b]
num2 = random.uniform(1.5, 5.5)
print(f"uniform(1.5, 5.5): {num2}")
# 生成多个随机浮点数
numbers = [random.uniform(0, 10) for _ in range(5)]
print(f"5个随机数: {numbers}")
控制精度
import random
# 保留2位小数
num = round(random.uniform(10, 20), 2)
print(f"保留2位小数: {num}")
# 保留3位小数
num = round(random.uniform(100, 200), 3)
print(f"保留3位小数: {num}")
# 生成特定位数的随机浮点数
def random_float_precision(start, end, decimal_places=2):
return round(random.uniform(start, end), decimal_places)
print(f"自定义精度: {random_float_precision(0, 1, 4)}")
实际应用案例
案例1:温度传感器模拟
import random
import time
def simulate_temperature_sensor():
"""模拟温度传感器读数"""
base_temp = 25.0 # 基准温度
for _ in range(5):
# 添加随机波动 (-2.0, 2.0)
temperature = base_temp + random.uniform(-2.0, 2.0)
temperature = round(temperature, 1)
print(f"当前温度: {temperature}°C")
time.sleep(0.5) # 模拟读取间隔
simulate_temperature_sensor()
案例2:股价波动模拟
import random
def simulate_stock_prices():
"""模拟股票价格变化"""
price = 100.0
prices = []
for _ in range(10):
# 价格波动范围 -5% 到 +5%
change = price * random.uniform(-0.05, 0.05)
price += change
price = round(price, 2)
prices.append(price)
return prices
stock_prices = simulate_stock_prices()
print(f"模拟股价变化: {stock_prices}")
print(f"最高价: {max(stock_prices)}")
print(f"最低价: {min(stock_prices)}")
案例3:机器学习数据生成
import random
def generate_training_data(samples=5):
"""生成机器学习训练数据"""
data = []
for _ in range(samples):
# 生成特征 (x, y) 和标签
x = round(random.uniform(0, 10), 2)
y = round(random.uniform(0, 10), 2)
# 基于特征计算标签 (加入噪声)
label = round(3*x + 2*y + random.gauss(0, 1), 2)
data.append({
'features': (x, y),
'label': label
})
return data
training_data = generate_training_data()
for i, sample in enumerate(training_data):
print(f"样本 {i+1}: 特征={sample['features']}, 标签={sample['label']}")
案例4:游戏物理引擎
import random
class Particle:
"""简单粒子系统"""
def __init__(self):
self.x = random.uniform(0, 100)
self.y = random.uniform(0, 100)
self.vx = random.uniform(-2, 2)
self.vy = random.uniform(-2, 2)
self.life = random.uniform(0.5, 2.0) # 粒子生命周期
def update(self):
self.x += self.vx
self.y += self.vy
self.life -= 0.1
def is_alive(self):
return self.life > 0
# 创建粒子系统
particles = [Particle() for _ in range(5)]
for i, particle in enumerate(particles):
print(f"粒子{i+1}: 位置({particle.x:.2f}, {particle.y:.2f}), 生命周期: {particle.life:.2f}")
高级随机数生成
import random
import numpy as np
# 使用numpy生成随机浮点数
np_random = np.random.uniform(0, 1, 5)
print(f"NumPy随机数: {np_random}")
# 生成服从正态分布的随机浮点数
normal_random = [random.gauss(0, 1) for _ in range(5)]
print(f"正态分布随机数: {normal_random}")
# 生成服从指数分布的随机浮点数
exponential_random = [random.expovariate(1.0) for _ in range(5)]
print(f"指数分布随机数: {exponential_random}")
实用函数封装
import random
from typing import List, Tuple
class RandomFloatGenerator:
"""随机浮点数生成器类"""
@staticmethod
def between(start: float, end: float, decimals: int = None) -> float:
"""生成指定范围的随机浮点数"""
num = random.uniform(start, end)
if decimals is not None:
num = round(num, decimals)
return num
@staticmethod
def list_between(start: float, end: float, count: int,
decimals: int = None) -> List[float]:
"""生成多个随机浮点数"""
return [RandomFloatGenerator.between(start, end, decimals)
for _ in range(count)]
@staticmethod
def with_probability(probability: float) -> bool:
"""按概率返回True/False"""
return random.random() < probability
# 使用示例
gen = RandomFloatGenerator()
print(f"5-10之间的随机数: {gen.between(5, 10, 2)}")
print(f"3个0-1之间的随机数: {gen.list_between(0, 1, 3, 4)}")
print(f"70%概率返回True: {gen.with_probability(0.7)}")
这些案例涵盖了Python生成随机浮点数的常见场景,你可以根据具体需求选择合适的方法。random.uniform() 是最通用的选择,而 random.random() 则适用于需要 [0, 1) 范围的情况。