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

조회 수: 17 (최근 30일)
Devin
Devin 2013년 11월 4일
댓글: Walter Roberson 2024년 11월 5일 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??

답변 (1개)

ag
ag 2024년 11월 5일 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!

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by