import matplotlib.pyplot as plt
import random
import math
# 线性同余法生成随机数
def linear_congruential_generator(n, m=9600, alpha=17, c=19, Z0=5):
random_numbers = []
Z = Z0
for _ in range(n):
Z = (alpha * Z + c) % m
random_numbers.append(Z / m)
return random_numbers
# 开方取中数法生成随机数
def square_middle_method(n):
random_numbers = []
for _ in range(n):
seed = random.random()
random_number = math.sqrt(seed)
random_numbers.append(random_number)
return random_numbers
# Excel生成随机数
def excel_random_numbers(n):
random_numbers = []
for _ in range(n):
random_number = random.uniform(0, 1)
random_numbers.append(random_number)
return random_numbers
# 统计频率并绘制频率分布图
def plot_frequency_distribution(random_numbers, method_name):
bins = [i / 10 for i in range(11)]
frequencies = [0] * 10
for number in random_numbers:
for i in range(10):
if bins[i] <= number < bins[i+1]: frequencies[i] += 1 break plt.bar(bins[:-1], frequencies, width=0.1, align='edge', alpha=0.7, label=method_name) # 生成随机数样本数据 n = 500 linear_congruential = linear_congruential_generator(n) square_middle = square_middle_method(n) excel = excel_random_numbers(n) # 绘制频率分布图 plot_frequency_distribution(linear_congruential, "Linear Congruential") plot_frequency_distribution(square_middle, "Square Middle") plot_frequency_distribution(excel, "Excel") plt.xlabel('Interval') plt.ylabel('Frequency') plt.title('Comparison of Random Number Generation Methods') plt.legend() plt.show()

苏ICP备18039385号