用 Python 编写程序,用于查找给定方程式中随机数的期望值
pythonserver side programmingprogramming更新于 2025/12/18 3:56:17
假设我们有一个数字 n。考虑 x = rand() mod n,其中 rand() 函数随机均匀地生成介于 0 和 10^100(含)之间的整数。并且
$$Y = \sqrt{x+\sqrt{x+\sqrt{x+\sqrt{x+...}}}}$$
我们必须找到 Y 的预期值。n 的值将在 1 和 5*10^6 范围内。
因此,如果输入为 n = 5,则输出将为 1.696
要解决这个问题,我们将遵循以下步骤 −
- err := 2235.023971557617
- max_n := 5 * 10^6
- pref := 列表最初包含单个 0
- 对于范围为 1 到 5 * 10^6 的 i,执行
- 在 pref 末尾插入 (pref 的最后一项 + (1 +(4*i + 1)^0.5) * 0.5
- 如果 n < max_n,则
- 返回 pref[n - 1] / n
- 否则,
- total :=(4 *(n - 1) + 5)^1.5 / 6 - 5^1.5 / 6 - err
- ans := 0.5 + total /(2 * n)
- 返回 ans
示例
让我们看看下面的实现以便更好地理解 −
def solve(n): err = 2235.023971557617 max_n = 5 * 10**6 pref = [0] for i in range(1, 5 * 10**6): pref.append(pref[-1] + (1 + (4 * i + 1)**0.5) * 0.5) if n < max_n: return pref[n - 1] / n else: total = (4 * (n - 1) + 5)**1.5 / 6 - 5**1.5 / 6 - err ans = 0.5 + total / (2 * n) return ans n = 5 print(solve(n))
输入
5
输出
1.69647248786
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

