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

0-1区间随机游走实验结果偏离y=x曲线的问题排查

问题原因与修复方案

核心错误点

  • 变量拼写错误:函数内X_Current = X_Star是笔误,应为X_Current = X_Start,这个错误导致每次试验的初始位置完全偏离传入的起始值,直接破坏逻辑基础。
  • 步长逻辑错误:题目要求每次移动前计算当前点到0和1的最小距离作为步长,但你的代码仅用初始起始值计算一次步长并重复使用,未随当前位置更新步长,完全违背规则,导致移动逻辑错误。

修复后的代码

修正上述错误后,代码可正确模拟过程,得到符合预期的y=x曲线结果:

from random import choice
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

def Experiment(X_Start) -> float:
    Num_Trials = 1000
    Success = 0

    for Trial in range(Num_Trials):
        X_Current = X_Start  # 修正拼写错误
        while 0 < X_Current < 1:
            # 每次循环重新计算当前位置的步长
            Movement_Radius = min(X_Current, 1 - X_Current)
            if choice([0, 1]):
                X_Current += Movement_Radius
            else:
                X_Current -= Movement_Radius

        if X_Current == 1:
            Success += 1

    return Success / Num_Trials, X_Start

if __name__ == '__main__':
    results = {'X_Start': [], 'Probability': []}
    n = 10  # 对应1024个均匀点
    total_points = 2**n + 1

    for i in range(total_points):
        prob, x_initial = Experiment(i / (total_points - 1))  # 确保最后一个点为1.0
        results['X_Start'].append(x_initial)
        results['Probability'].append(prob)
    
    df = pd.DataFrame(results)

    plt.figure(figsize=(12,8))
    sns.scatterplot(data=df, x='X_Start', y='Probability', marker='x', color='red')
    # 添加预期的y=x对比曲线
    plt.plot([0,1], [0,1], color='blue', linestyle='--', label='Expected y=x')
    plt.xlabel('X_Start')
    plt.ylabel('Probability of Success')
    plt.title(f'Probability of Success vs X_Start with {2**n} points')
    plt.legend()
    plt.show()
    plt.close()

补充说明

  • 修正步长逻辑后,每次移动都会向边界靠近:例如当前位置为0.3时步长是0.3,反面直接到0,正面到0.6;到0.6后步长变为0.4,反面到0.2,正面直接到1。这个对称随机游走过程的成功概率确实符合y=x规律,起始点x到达1的概率就是x。
  • 原代码n=5仅生成33个点,改为n=10即可得到1024个均匀点,符合问题要求。
  • 移除了无用的random和gc导入,简化代码结构。

内容的提问来源于stack exchange,提问作者Pieter van der Dussen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:03:26