I am using 2021b. I wanted to look at the convergence rate of a iteration algorithm for Pi, using continued fraction. The formula was for wikipedia https://en.wikipedia.org/wiki/Pi#Continued_fractions.
by iteration 10 steps,precision up to 6 digits after dot
17steps, 10 digits
18steps, 13 digits
19steps, 500+ digits
the same above 20 steps.
It seems like Matlab saw through my intention and showed me the "exact" value directly...
This should be a bug, since I tried the same algorithm in both python and scheme, the behaviors are normal.
Now the question is, why is this happenning? I never tried to touch the "exact" value of pi in the code. (the code is below, very short)
% calculate pi using continued fraction formula
% pi=4/(1+1^2/(3+2^2/(5+3^2/7+...
% e.g. take N=15, pi=3.141592653606706
function p=calc_pi(N)
p=conti_frac(0,N);
p=vpa(p,500);
end
function p=conti_frac(k,N)
if k==0
p=(0+4/conti_frac(1,N));
elseif k==N
p=2*k-1;
else
p=2*k-1+k*k/conti_frac(k+1,N);
end
end
You’re doing computations using doubles (64-bit floating point), so you will never be able to compute more than 15 or 16 digits. There just aren’t any more in a double.
What probably happens is that the vpa
function decides that the input is so close to pi, you must mean pi, and it substitutes the actual value of pi.
You can verify this is the case by writing
vpa(3.14159265358979, 500)
Add and remove digits to find out how many digits you need for the function to recognize the value of pi.