Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create PI sequentially in Ruby

Out of pure interested, I'm curious how to create PI sequentially so that instead of the number being produced after the outcome of the process, allow the numbers to display as the process itself is being generated. If this is the case, then the number could produce itself, and I could implement garbage collection on previously seen numbers thus creating an infinite series. The outcome is just a number being generated every second that follows the series of Pi.

Here's what I've found sifting through the internets :

This it the popular computer-friendly algorithm, The Machin-like Algorithm :

def arccot(x, unity)
   xpow = unity / x
   n = 1
   sign = 1
   sum = 0
   loop do
       term = xpow / n
       break if term == 0
       sum += sign * (xpow/n)
       xpow /= x*x
       n += 2
       sign = -sign
   end
   sum
end

def calc_pi(digits = 10000)
   fudge = 10
   unity = 10**(digits+fudge)
   pi = 4*(4*arccot(5, unity) - arccot(239, unity))
   pi / (10**fudge)
end

digits = (ARGV[0] || 10000).to_i
p calc_pi(digits)
like image 275
Trip Avatar asked Jun 29 '10 03:06

Trip


1 Answers

To expand on "Moron's" answer: What the Bailey-Borwein-Plouffe formula does for you is that it lets you compute binary (or equivalently hex) digits of pi without computing all of the digits before it. This formula was used to compute the quadrillionth bit of pi ten years ago. It's a 0. (I'm sure that you were on the edge of your seat to find out.)

This is not the same thing as a low-memory, dynamic algorithm to compute the bits or digits of pi, which I think what you could mean by "sequentially". I don't think that anyone knows how to do that in base 10 or in base 2, although the BPP algorithm can be viewed as a partial solution.

Well, some of the iterative formula for pi are also sort-of like a sequential algorithm, in the sense that there is an iteration that produces more digits with each round. However, it's also only a partial solution, because typically the number of digits doubles or triples with each step. So you'd wait with a lot of digits for a while, and the whoosh a lot more digits come quickly.

In fact, I don't know if there is any low-memory, efficient algorithm to produce digits of any standard irrational number. Even for e, you'd think that the standard infinite series is an efficient formula and that it's low-memory. But it only looks low memory at the beginning, and actually there are also faster algorithms to compute many digits of e.

like image 51
Greg Kuperberg Avatar answered Sep 19 '22 03:09

Greg Kuperberg