Finding PI in JavaScript
Chudnovsky algorithm
To date, one of the fastest and most efficient algorithms for calculating PI is considered to be the Chudnovsky algorithm
The principle of this algorithm is the basis of the 2019 record for the calculation of PI — 31.4 trillion digits
Skipping all mathematical transformations
We get
To translate this formula into code, we need to know what Q and T are
Q and T — Mathematical functions which are expressed as
This looks a little confusing, but let’s go over it step by step
Define the constants
Implementing the algorithm for calculating P, Q and T
Find PI
We need to decide to what decimal place we will count to. This algorithm at each iteration allows us to find 14.1816474627… significant digits
You can try to calculate it yourself
After calculating the value, let’s put it in a constant
Write a function to calculate PI
Finally, we are ready to count the decimal places
Checking the result
Yeah? Mistake!
We were able to find the number of characters we are interested in, now we can breathe easy and apply the obtained value in practice
But if you look closely, you can find an error
Compare
3.1415926535897935600871733186
3.1415926535897932384626433832
The first value was obtained by us, the second was taken from the Internet
The divergence starts after 15 characters. That is how many significant characters the double type has in JavaScript
Working on the bugs
To calculate more characters, we need to understand how to work with large numbers in JS
The BigNumber.js library for working with large numbers might be suitable for this purpose
But before that we need to simplify the formula a bit by removing the fractional degree from it
Rewrite the old constant definitions and add new ones. At the same time, we take unnecessary calculations out of the compute_PQT method
Rewrite our calculation functions
Second try
Compare
3.1415926535897935600871733186
3.1415926535897932384626433833
3.1415926535897932384626433832
Good!
Only the last digit is different, and that’s because we use toFixed, which rounds up the number when converting it to a string
RangeError: Maximum call stack size exceeded
This error occurs when the node.js runtime has a call stack overflow
It can be avoided by giving the runtime the ability to clear the stack
Complete code can be found on GitHub