Skip to content
Advertisement

Trying to accurately get 100 digits of pi with Chudnovsky’s algorithm in PYTHON

I am trying to teach myself Chudnovsky’s algorithm using Python and this wikipedia page:

https://en.wikipedia.org/wiki/Chudnovsky_algorithm

On the wiki, I am focused on the “high performance iterative implementation, [that] can be simplified to”:

enter image description here

I tried to code up the equation on the far right that is using the Sigma symbol. I am familiar with Python but am not that great at math. The goal I set for myself is to see if I can accurately print out at least 100 digits of pi.

There are 5 sets of parentheses in the formula so I tried to code up each of the 5 different components. I also wrote a function that does factorials because factorials are used in 3 of the 5 components/parentheses.

Here’s my 23 lines of working code, can someone please help me understand why it does not ACCURATELY go to 100 digits? It accurately goes to the 28th digit: 3.1415926535897932384626433832. Then for the 29th digit it says 8 but it should be 7…

JavaScript

Thank you for any assistance that you’re able to provide.

Advertisement

Answer

  • Set the decimal precision at the start of the file so that it is applied to all subsequent operations:

    JavaScript
  • Convert either or both operands to Decimal before dividing or multiplying:

    JavaScript

Result – accurate to 98 d.p. (100 s.f. minus rounding error):

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement