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

17 Ansichten (letzte 30 Tage)
Devin
Devin am 4 Nov. 2013
Kommentiert: Walter Roberson am 5 Nov. 2024 um 5:40
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??

Antworten (1)

ag
ag am 5 Nov. 2024 um 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!

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Tags

Noch keine Tags eingegeben.

Community Treasure Hunt

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

Start Hunting!

Translated by