I want to find a specific sequence of digits in the decimals of PI and that involves first computing PI to (quite possibly) infinity. The problem is that I don't know how to make a variable store that many digits or how to just use the newly computed digit so I can compare it to my sequence.
So how can I calculate PI and keep only the last decimal as an integer?
Thanks in advance.
This kind of problem can be solved very elegantly using lazy evaluation, like the one found in Haskell. Or using generators in Python, producing at most one number of Pi at a time, and checking against the corresponding position in target value that's being searched.
The advantage of either approach is that you don't have to generate a (potentially) infinite sequence of numbers, only generate as much as needed until you find what you're looking for. Of course, if the specific sequence really doesn't appear in the number Pi the algorithm will iterate forever, but at least the computer executing the program won't run out of memory.
Alternatively: you could use the BBP Formula, or a similar algorithm which allows the extraction of a specific digit in Pi.
You can use an iterative algorithm for calculating Pi, for example, the Gauss–Legendre algorithm.
To implement it, you will need a library that does arbitrary-precision arithmetic; one such library is GMP.
Apparently, someone has done most of the work for you: http://gmplib.org/pi-with-gmp.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With