Program to find expected value of given equation for random numbers in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n. Consider x = rand() mod n, where rand() function generates integers between 0 and 10^100 (both inclusive) uniformly at random. And

$$Y = \sqrt{x+\sqrt{x+\sqrt{x+\sqrt{x+...}}}}$$

We have to find the expected value of Y. The value of n will be in range 1 and 5*10^6.

So, if the input is like n = 5, then the output will be 1.696

To solve this, we will follow these steps −

  • err := 2235.023971557617
  • max_n := 5 * 10^6
  • pref := a list initially contains a single 0
  • for i in range 1 to 5 * 10^6, do
    • insert (last item of pref + (1 +(4*i + 1)^0.5) * 0.5 at the end of pref
  • if n < max_n, then
    • return pref[n - 1] / n
  • otherwise,
    • total :=(4 *(n - 1) + 5)^1.5 / 6 - 5^1.5 / 6 - err
    • ans := 0.5 + total /(2 * n)
    • return ans

Example

Let us see the following implementation to get better understanding −

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))

Input

5

Output

1.69647248786
raja
Published on 11-Oct-2021 07:34:32
Advertisements