'How can I use the method init in this function [closed]

import math
def pi_approx(N):
product=1
  cycle=N
  if N>=2:(
    for j in range(0,cycle):(
      x=2  
      
      for i in range(0,cycle-j):(
    
        operation=2+math.sqrt(x)
        x=operation
      #print('the value of x: ',math.sqrt(x))
     )
      product = product*(math.sqrt(x)/2)
      #product = product/2
      #print('the value of product: ', product)
)
    product=product*(math.sqrt(2)/2)     

  #print(product)
  pi_est=2/product
  different = math.fabs(pi_est-math.pi)
  #print(different)
 ) return different<1e-7}

This expression can be used to approximate pi:

π=2/V

where

V=(√2)/2 * √(2+√2)/2 * √(2+√(2+√2))/2*.....

I am trying to reduce the time of operation in this function. I want to calculate when N=1000000 and get the difference or error in my calculation.



Solution 1:[1]

You are calculating each term from scratch when finding V. Instead, you should recognize the recurrence relation:

V_i = sqrt(2 + V_(i-1))

With this in mind, it's very clear how to write performant code for this algorithm.

import math
import sys

def calculate_pi(iterations):
    numerator = 0
    V = 1
    for i in range(iterations):
        numerator = math.sqrt(2 + numerator) 
        V *= numerator / 2

    return 2 / V

if __name__ == "__main__":
    iterations = int(sys.argv[1])
    print(calculate_pi(iterations))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Antonio Leonti