How to write a Matlab program to calculate pi using Gregory/Leibnitz series

16 views (last 30 days)
A sample run of the program:
Enter number of terms to calculate (1000 or more): 999
You entered: 999, which is too few terms
The number of terms is set to 1000
pi calculated by Gregory/Leibnitz at end of loop: 3.1405926538
Matlab value of pi: 3.1415926536
Difference with Matlab value of pi at end of loop: -0.0009999997
Graph of difference from Matlab pi for first 100 terms is in Figure 1
Program ended
How do I get started with this program??

Answers (1)

ag
ag on 5 Nov 2024 at 5:15
Hi Devin,
The below code demonstrates how to calculate an approximation of (\pi) using the Gregory-Leibniz series and compare it with MATLAB's built-in value of (\pi). It also demonstrates how to create a graph the difference from MATLAB's (\pi) for the first 100 terms:
% Prompt the user to enter the number of terms
% numTerms = input('Enter number of terms to calculate (1000 or more): ');
numTerms = 1001;
% Check if the entered terms are less than 1000
if numTerms < 1000
fprintf('You entered: %d, which is too few terms\n', numTerms);
numTerms = 1000;
fprintf('The number of terms is set to 1000\n');
end
% Initialize variables
piApprox = 0;
differences = zeros(1, min(100, numTerms)); % Store differences for first 100 terms
% Calculate pi using the Gregory-Leibniz series
for k = 0:numTerms-1
piApprox = piApprox + ((-1)^k) / (2*k + 1);
% Store the difference for the first 100 terms
if k < 100
differences(k+1) = abs(piApprox * 4 - pi);
end
end
% Multiply by 4 to get the approximation of pi
piApprox = piApprox * 4;
% Display the results
fprintf('pi calculated by Gregory/Leibnitz at end of loop: %.10f\n', piApprox);
pi calculated by Gregory/Leibnitz at end of loop: 3.1425916543
fprintf('Matlab value of pi: %.10f\n', pi);
Matlab value of pi: 3.1415926536
fprintf('Difference with Matlab value of pi at end of loop: %.10f\n', piApprox - pi);
Difference with Matlab value of pi at end of loop: 0.0009990007
% Plot the difference for the first 100 terms
figure;
plot(1:100, differences, 'b-', 'LineWidth', 2);
xlabel('Number of Terms');
ylabel('Difference from MATLAB pi');
title('Graph of difference from MATLAB pi for first 100 terms');
grid on;
fprintf('Graph of difference from Matlab pi for first 100 terms is in Figure 1\n');
Graph of difference from Matlab pi for first 100 terms is in Figure 1
fprintf('Program ended\n');
Program ended
Hope this helps!

Categories

Find more on Programming in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!