How to write a Matlab program to calculate pi using Gregory/Leibnitz series
16 views (last 30 days)
Show older comments
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??
0 Comments
Answers (1)
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);
fprintf('Matlab value of pi: %.10f\n', pi);
fprintf('Difference with Matlab value of pi at end of loop: %.10f\n', piApprox - pi);
% 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');
fprintf('Program ended\n');
Hope this helps!
1 Comment
Walter Roberson
on 5 Nov 2024 at 5:40
We do not recommend providing complete code to answer homework questions.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!