Search code examples
pythontype-conversionseriespi

Compute the value of π using the following series (Matlab conversion)


I just started using Python and can't really get the hang of it..

I wrote the code in Matlab but is hard to covert it the right way in Python.

Image

Could you please help?

 x=0;
    for i=1:1000
         x=x+(1/((((2*i)-1)^2)*(((2*i)+1^2))));
         z=sqrt((x*16)+8);
         error=abs(z-pi);
         if (error < 10^-8)
            i
            break
         end
    end

Thank you


Solution

  • import math
    

    ...

    x = 0
    for i in range(1,1001):
        x = x + (1 / (((2 * i - 1) ** 2) * ((2 * i + 1) ** 2)))
        z = math.sqrt((x * 16) + 8)
        error = abs(z - math.pi)
        if error < 10 ** -8:
            print(i)
            break