Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมหาค่าคาดหวังของสมการกรณีสุ่มใน Python

ให้ n, x = rand() mod n (rand สุ่ม 0 ถึง 10^100) หาค่าคาดหวังของ Y = sqrt(x + sqrt(x + sqrt(x + ...)))

ตัวอย่าง: n=5 → 1.696...

ขั้นตอน

  1. Pre-compute Prefix Sum สำหรับ n ≤ 5×10^6
  2. สูตร Closed-form สำหรับ n > 5×10^6 ใช้ Integral Approximation

ตัวอย่างโค้ด

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))  # Output: 1.69647248786

อินพุต

5

เอาต์พุต

1.69647248786