You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

验证day_sim(n)随n增大趋近sqrt(pi*n/2)的代码问题求助

问题原因定位
  • 缺少必要依赖导入:代码用到了math计算平方根、matplotlib.pyplot绘图,但都没有提前导入,运行会直接报错
  • 重复定义函数:day(n)函数被重复定义了两次,属于冗余代码
  • 核心逻辑错误:该结论是期望层面的趋近规律,你当前代码对每个n仅执行1次随机实验,单次结果的随机波动极大,完全无法体现统计规律,需要对每个n重复多次实验后取平均值
  • 变量作用域与命名冲突问题:
    1. day_sim函数内部定义的n_trails属于局部变量,你在全局作用域调用day_sim(n_trails)时会因为找不到该变量报错
    2. 函数内部把实验结果变量命名为day_sim,和函数名重名,会引发命名污染
    3. 函数参数是n,内部循环又把n作为循环变量,逻辑混乱
  • 冗余代码:randomgen函数里的np.random.randint(low = 0, high = n)执行后没有返回也没有赋值,属于无效代码
  • 绘图逻辑问题:每次循环都重复设置坐标轴范围,且代码末尾没有加plt.show(),最终不会显示图像
修正后可运行代码
import random
import math
import matplotlib.pyplot as plt

def randomgen(n):
    return random.randint(0, n-1)

def day(n):
    result = []
    cur_random = randomgen(n)
    count = 0
    while cur_random not in result:
        result.append(cur_random)
        cur_random = randomgen(n)
        count += 1
    return count

def day_sim(max_n=1000, repeat_times=200):
    # 对每个n做repeat_times次实验取平均降低波动
    for n in range(2, max_n+1, 20):
        total = 0
        for _ in range(repeat_times):
            total += day(n)
        avg_day = total / repeat_times
        sq_rt = math.sqrt(math.pi * n / 2)
        print(f"n = {n}, 实验均值={avg_day:.2f}, 理论值={sq_rt:.2f}, 绝对差={abs(sq_rt - avg_day):.2f}")
        plt.scatter(n, avg_day, color='skyblue', label='实验均值' if n==2 else "")
        plt.scatter(n, sq_rt, color='red', label='理论值' if n==2 else "")
    plt.xlabel("n")
    plt.ylabel("值")
    plt.legend()
    plt.xlim(0, max_n)
    plt.show()

# 调用函数,n最大到1000,每个n重复200次实验取平均
day_sim(max_n=1000, repeat_times=200)

内容的提问来源于stack exchange,提问作者riven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 02:24:03