MATLAB question: Leibniz found that pi can be approximated by the following seri
ID: 3028559 • Letter: M
Question
MATLAB question:
Leibniz found that pi can be approximated by the following series: pi = 4 sigma_n=0^infinity (-1)^n/2n + 1. Madhava (with Leibniz) later suggested an alternative series: pi = squareroot 12 sigma_n=0^infinity (-3)^(-n)/2n + 1. In this exercise, you are asked to write a function testpi.m to compare how fast the two series can approximate the value of pi for a given tolerance. The function should have the following declearation: function [api, nterm] = testpi(tol, method) where tol is the input tolerance defined as the absolute difference between the approximated pi and the default value of pi in MATLAB divided by the default value. Method is a string input being either 'Leibniz' or 'Madhava'. The function outputs are the approximated value of pi api and the number of terms nterm in the series needed to compute the approximate value. In the function, you may want to consider the relationship between abs(api-pi)/pi and tol as a condition to truncate n in the two series above. Give the function a description. In the following exercises, set the tolerance to 10^-7. Set p4a = evalc ('help testpi'). For the Leibniz series, what is the approximated value of pi and how many terms of the series are needed to compute that value? Put the answers in p4b and p4c, respectively. For the Madhava series, what is the approximated value of pi and how many terms of the series are needed to compute that value? Put the answers in p4d and p4e, respectively. Which method converges faster? Give answer in p4f = '... series converges faster'.Explanation / Answer
clear all;
close all;
tol=10^(-7);
[p4b,p4c]=testpi(tol,'Leibniz');
[p4d,p4e]=testpi(tol,'Madhava');
if (p4c<p4e)
p4f='Leibniz series convergence faster';
else
p4f='Madhava series convergence faster';
end
///// Function body is as follows////
function [api,nterm]=testpi(tol,method)
str1='Leibniz';
str2='Madhava';
if (str1==method)
sum=0;
for n=0:100000000000
sum=sum+4*(-1)^n/(2*n+1);
if abs(sum-pi)/pi<tol
break;
end
end
else
sum=0;
for n=0:10000000000000
sum=sum+sqrt(12)*(-3)^(-n)/(2*n+1);
if abs(sum-pi)/pi<tol
break;
end
end
end
api=sum;
nterm=n;
p4b =
3.1416
p4c =
3183098
p4d =
3.1416
p4e =
11
p4f =
Madhava series convergence faster
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.