1
votes

I found an exciting Link on calculating pi in Javascript: http://ajennings.net/blog/a-million-digits-of-pi-in-9-lines-of-javascript.html?utm_source=Iterable&utm_medium=email&utm_campaign=the-overflow-newsletter&utm_content=10-03-19

I did never program in Javascript, but I managed to translate it into MATLAB using the 'Symbolic Math Toolbox'. Here my code (containing the Javascript code as MATLAB comment lines)

%% A Million Digist of Pi in 9 Lines of Javascript

% http://ajennings.net/blog/a-million-digits-of-pi-in-9-lines-of-javascript.html

% let i = 1n;
% let x = 3n * (10n ** 1020n);
% let pi = x;
% while (x > 0) {
%         x = x * i / ((i + 1n) * 4n);
%         pi += x / (i + 2n);
%         i += 2n;
% }
% console.log(pi / (10n ** 20n));


% MATLAB Code

n = 1000;   % Number of digits
k = sym(1);
x = 3 * (10^sym(n));
pi = x;

tic
while x > 1/2
    x = x * k / ((k + 1) * 4);
    pi = pi + x /(k + 2);
    k = k +2;
end
fix(pi)
toc

My question now:

Why is the Javascript faster than MATLAB using the Symbolic Math Toolbox? Note: The code is using unlimited integer. So in other words: Why is the Javascript 'infinite digits integer' faster than the symbolic integer in Matlab. Or isn't it?

It has taken 16s for 1000 digits in MATLAB, and not less than 1s (see the link)!

This seems a bit strange to me, as normally MATLAB is really fast (not the fastest, I know).

If someone asks himself, why the hell did you do that? First, it is fun - and second: I need MATLAB and I like it

Thanks for any answer!

1

1 Answers

1
votes

The symbolic math toolbox is for - as the name says - symbolic mathematics, that means it does algebraic computations, but that is something that takes a lot of computation and is therefore quite slow. JavaScript does not use algebraic computations, it just uses a built in BigInt type. Try to do the same without the sym and you see it will be a lot faster, you could for instance use uint64 integers:

n = uint64(18);   % Number of digits
k = uint64(1);
x = 3 * uint64(10)^n;
pi = x;

tic
ctr = 0
while x > 1/2
    ctr = ctr + 1;
    x = x * k / ((k + 1) * 4);
    pi = pi + x /(k + 2);
    k = k +2;
end
fix(pi)
toc