Search code examples
pythonalgorithmpi

Calculate N-th decimal digit of pi


What I need:

Function to calculate N-th decimal digit of Pi. Example:

>>> pi_digit(1)
1
>>> pi_digit(2)
4
>>> pi_digit(3)
1
>>> pi_digit(4)
5

What did I tried:

While searching, found that code. It actually does what I need except one thing - it calculates all N digits, while I need only last. Is this possible to accomplish in efficient way? (if I just slice string for last character it wouldn't be so fast). Thanks in advance.

Why I need it:

I'm going to put that script, which would append digits to text file, onto my server and leave it for 20-30 days, and check the output.


Solution

  • see:

    Unbounded Spigot Algorithms for the Digits of Pi

    Jeremy Gibbons

    The program under discussion is written in Haskell [5], a lazy functional programming language. As a secondary point of this paper, we hope to convince the reader that such languages are excellent vehicles for expressing mathematical computations, certainly when compared with other general-purpose programming languages such as Java, C, and Pascal, and arguably even when compared with computer algebra systems such as Mathematica.

    https://www.cs.ox.ac.uk/jeremy.gibbons/publications/spigot.pdf

    it can be implemented with pidigits

    https://github.com/transmogrifier/pidigits

    pidigits is avalaible through Python Package Index (PyPI) using pip.

    >>> pip install --upgrade pidigits