Approximating Pi by Using Ramanujan's Formula

Hi. This is my first post so please let me know if I violate any kind of rules. Thank you in advance.
I intend to approximate pi by summing a specified number of terms (k). The output I got was nowhere near what I wanted. Could someone help me please?
Here is the equation I'm using:
And there is the code:
k = input('Number of terms: ');
pi2 = sum(factorial([1:k]*4).*(1103+26390*[1:k]));
pi2 = pi2/((factorial([1:k])^4)*396^(4*[1:k]));
pi2 = (pi2*(2*sqrt(2)/9801))^(-1);
fprintf('Method: %.20f\n', pi2);

댓글 수: 5

You are taking sum of the numerator only, and then dividing by the vector that is the denominator.
Note: you also need to vectorize your code. You are working with vectors derived from 1:k so you need to use vector operations such as .^
Stephen23
Stephen23 2020년 9월 1일
편집: Stephen23 2020년 9월 1일
Note: as the factorial documentation explains, you will only get an exact result when its input is 21 or less. This means in Ramanujan's Formula the term (4*k)! restricts k to 5 or less. Larger values of k will return inexact values for that factorial (inexact values can be calculated up to 170!).
Peter Wang
Peter Wang 2020년 9월 1일
편집: Peter Wang 2020년 9월 1일
Thank you both so much! I'm new to Matlab and I always want to solve everything in one step. Learned a lot from Stephen's answer!
Beyond 21 you should probably be using the Symbolic Toolbox
Bruno Luong
Bruno Luong 2020년 9월 1일
편집: Bruno Luong 2020년 9월 1일
You already get inexact result even for one term since the division in double is inexact. As long as D and N is finite the calculation is OK (and inexact anyway for partial sum).
Actually the result doesn't change after N=2 and it's already equal to 1/pi at 15 digits !!!
>> N=1:42;
>> Ramanujan=@(N)(2*sqrt(2)/9801)*sum((factorial(4*(0:N)).*(1103+26390*(0:N))./((factorial(0:N).^4).*(396.^(4*(0:N))))));
>> A=arrayfun(Ramanujan, N); % only the last term is NaN
>> A==1/pi
ans =
1×42 logical array
Columns 1 through 26
0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Columns 27 through 42
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0

댓글을 달려면 로그인하십시오.

 채택된 답변

Stephen23
Stephen23 2020년 9월 1일

1 개 추천

>> k = 5;
>> V = 0:k;
>> N = factorial(4.*V).*(1103+26390.*V);
>> D = (factorial(V).^4).*(396.^(4.*V));
>> (2*sqrt(2)/9801)*sum(N./D)
ans = 3.183098861837907e-01
>> 1./pi
ans = 3.183098861837907e-01

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Biological and Health Sciences에 대해 자세히 알아보기

태그

질문:

2020년 9월 1일

편집:

2020년 9월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by