Why does Matlab round this error to 0, even though I know it isn't precisely 0
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Anirudh Bhalekar
am 29 Aug. 2020
Kommentiert: Anirudh Bhalekar
am 29 Aug. 2020
I am trying to plot Ramanujan's Pi formula and observe how the errors are reducing as the number of iterations increases. However MATLAB simply outputs 0 after the first iteration even when I put the value of digits() to around 300. I know the formula doesn't calculate pi to a 100 decimals after the first iteration, in fact it's an additonal 8 decimal places per iteration after the first, yet it continues to output 0.0 as the value of the function - value of pi calculated to 300 digits. How can I fix this?
This is my code for the formula and the error function (I am using disp() at the end just to test the code).
% Ramanujan's Formula Plot %
rconst = sqrt(8)/9801;
rsum = 0;
rlim = 100;
plt3= 1:(rlim+1);
for n= 0:rlim
ctr = 1;
f4n = factorial(4*n);
fn = factorial(n);
num = (f4n * (1103+26390*n));
den = ((fn^4) * 396^(4*n));
rcalc = (num/den);
rtemp = (rconst * rcalc);
rsum = (rsum + rtemp);
rpi = (1/rsum);
plt3(n+1) = vpa(rpi);
ctr = ctr +1;
end
plot(plt3);
for ii = 1:41
var = abs(plt3(ii) - vpa(pi,334));
phi = sym(var);
disp(vpa(phi,334));
end
0 Kommentare
Akzeptierte Antwort
Steven Lord
am 29 Aug. 2020
All your calculations to compute rpi are being performed in double precision. By the time you call vpa on it it's too late, much like presenting a coupon at the store after the cashier has already taken your payment and given you your change back.
If you want to perform the calculations in arbitrary precision, start off by creating the data on which you want to operate as symbolic variables so you perform symbolic calculations.
rconst = sqrt(sym(8))/9801;
rsum = sym(0);
When you perform operations like / where one input is a double and the other a sym the result is performed symbolically. That's why I didn't need to convert 9801 into a sym; it will be automatically treated as a sym when the division is performed.
Another example later in the code:
ns = sym(n);
f4n = factorial(4*ns);
fn = factorial(ns);
2 Kommentare
John D'Errico
am 29 Aug. 2020
The other reason why you did not need to convert 9801 to a sym is because MATLAB stores the exact value of an integer when it is no larger than 2^53-1.
Siehe auch
Kategorien
Mehr zu Assumptions finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!