python - 根據均值和標準差生成隨機整數

wstong發表於2024-07-27
import numpy as np, pandas as pd, math

while True:
    mean, std_dev, num_samples = 105, 2.5, 100
    data = np.random.normal(loc=mean, scale=std_dev, size=num_samples)
    df = pd.DataFrame(data, columns=['value'])
    for i in range(len(df)):
        df['value'][i] = math.ceil(df['value'][i])  # 數字取整數,根據實際情況而定
    if 104 <= df['value'].mean().round(2) and df['value'].mean().round(2) <= 106:
        break
print(f"範圍: {df['value'].min()}-{df['value'].max()}")
print(f"平均: {df['value'].mean().round(2)}±{df['value'].std().round(2)}")
# 範圍: 97.0-111.0
# 平均: 104.96±2.51

相關文章