In: Mechanical Engineering
Another less efficient way to estimate pi is the Gregory-Leibniz series: pi = 4/1 -4/3 + 4/5 -4/7 + 4/9... . Use a while loop to approximate pi using this technique (5 points). Continue the calculations until the absolute value of the difference between the value of pi stored in MATLAB and the approximation is less than 0.001. Report the final approximation and the number of iterations required (5 points). Hint: to alternate the sign on each term use (-1) raised to a power.
The code is below:
---------------------------------------------------------------------------------------
clc;
p=0;
count=0;
i=0;
%fprintf('value of abs diff %1.16f \n',abs(pi-p));
while abs(pi-p) > 0.001
%fprintf('value of abs diff %1.16f \n',abs(pi-p));
p = p + (4*((-1)^i))/(2*i + 1);
count=count+1;
i=i+1;
end
fprintf('Number of iterations is %d \n',count);
fprintf('Value of Pi is %1.16f...\n',p);
------------------------------------------------------------------------------------------------------------------------
Also the m file can be downloaded from the following link:
https://drive.google.com/file/d/1stNHZ8cbiIMjkoX8nTQwmf_Eb1KCr53z
To run the m file , go to the specific folder and type leibniz
The output is shown below: