+ 1

How can I make it work faster? I need to find 30 000 digits of pi. Only js.

https://code.sololearn.com/WmSjyqjp0T2p/?ref=app

5th Mar 2021, 11:46 AM
Хусан Абдигафуров
Хусан Абдигафуров - avatar
4 Respostas
+ 2
It sounds like you already knew about the incorrect digits. If you need 10 times as many iterations to calculate each consecutive digit of PI, that's extremely inefficient. That's exponential time complexity. There are many PI calculation algorithms and many are more efficient than yours. A few are shown with implementations here: http://www.i4cy.com/pi/ To get more useful performance and correctness, I would replace with another algorithm. I copied one of the implementations at http://www.i4cy.com/pi/ to help you get an implementation that works in Sololearn's Code Playground: https://code.sololearn.com/WA2488a1A19A I couldn't find a working CDN for decimal.js so I copied it to my github pages repository. I don't understand all the underlying math but I hope that helps you. 1000 digits is correctly computed in less than a second with that algorithm but 30,000 will still take a long time to compute. I experimented with 10,000 and it takes over 10 seconds on my laptop. The browser typically doesn't allow JavaScript to run in the main thread more than a few seconds so you may want a technique like demonstrated here: https://code.sololearn.com/WAu6ci62d0L0/# to break up the calculation into smaller intervals.
5th Mar 2021, 7:55 PM
Josh Greig
Josh Greig - avatar
+ 1
Before optimizing it for speed, you should make it correct. I'm not sure why but one in every 5 or 6 digits is incorrect. This is what I get by giving 1000 to the prompt: 3.141593653590793239212643633279315384259670383750121440572600846263405273... The correct digits are 3.141592... The 3.141593... is wrong. After that one digit is wrong, the 6535 is correct but then it messes up again. 653590 should be 653589. Here is the correct first digits of PI to compare with: 3.1415926535897932384626433832795
5th Mar 2021, 6:13 PM
Josh Greig
Josh Greig - avatar
0
By increasing the number of iteration in for cycle i can make it work much more precise. But then it will work too slow or it won't work at all.
5th Mar 2021, 6:18 PM
Хусан Абдигафуров
Хусан Абдигафуров - avatar
0
Thanks a lot 😊
5th Mar 2021, 8:12 PM
Хусан Абдигафуров
Хусан Абдигафуров - avatar