Implement a function intpi n that estimates pi computing the

Implement a function intpi (n) that estimates pi computing the integral pi = 4 integral^1_0 squareroot 1 - x^2 dx The integral should be approximated using the following formula: integral^1_0 f(x) dx almostequalto delta x sigma^n-1_i=0 f(x_i) where delta x = 1/n where delta x = 1/n and x_i = delta x middot i. Report the output of your function for n = 10, 50, 100, 500, 1000, and 5000. Also report the true relative error (relative to the constant numpy.pi), as well as approximate relative error given the current estimate and the previous estimate (for each value of n after the first one).

Solution

from numpy import pi
from math import sqrt

def intpi(n):
estimated_pi = 0
delta = 1.0/n
for i in xrange(0, n):
estimated_pi += sqrt(1 - ((delta*i)**2))
  
estimated_pi = 4*delta*estimated_pi
relative_error = abs((estimated_pi - pi)/pi)
return (estimated_pi, relative_error)
prev_estimate = 0
for i in [10, 50, 100, 500, 1000, 5000]:
(estimated_pi, relative_error) = intpi(i)
print \"n : \" + str(i)
print \"Estimated value of pi : \" + str(estimated_pi)
print \"Relative error: \" + str(relative_error)
  
if prev_estimate != 0:
approx_error = abs((estimated_pi - prev_estimate)/estimated_pi)
print \"Error with previous estimate: \" + str(approx_error)
prev_estimate = estimated_pi

pastebin link in case indentation is messed up: http://pastebin.com/zXqVGCWG

 Implement a function intpi (n) that estimates pi computing the integral pi = 4 integral^1_0 squareroot 1 - x^2 dx The integral should be approximated using the

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site