Skip to content

Instantly share code, notes, and snippets.

@komasaru komasaru/pi_bbp.rb
Last active Aug 29, 2015

Embed
What would you like to do?
Ruby script to compute pi with BBP formula.
#!/usr/local/bin/ruby
#=======================================
# Computation of pi by BBP algorithm.
#=======================================
require 'benchmark'
class PiBbp
EPS = 1.0e-17 # Loop-exit accuration of the right summation
def comp_pi(d)
d -= 1
pi = (4 * s(1, d) - 2 * s(4, d) - s(5, d) - s(6, d)) % 1.0
printf("FRACTION : %.15f\n", pi)
printf("HEX DIGITS: %10x\n", (pi * 16 ** 10).truncate)
end
def s(j, d)
# Left sum
s = 0.0
k = 0
while k <= d
r = 8 * k + j
t = mod_exp(16, d - k, r)
t /= r.to_f
s += t % 1.0
s %= 1.0
k += 1
end
# Right sum
loop do
r = 8 * k + j
t = 16.0 ** (d - k) / r
break if t < EPS
s += t
s %= 1.0
k += 1
end
return s
end
def mod_exp(b, e, m)
return 1 if e == 0
ans = mod_exp(b, e / 2, m)
ans = (ans * ans) % m
ans = (ans * b) % m if e % 2 == 1
return ans
end
end
exit unless __FILE__ == $0
exit unless ARGV[0]
obj = PiBbp.new
res = Benchmark.realtime do
obj.comp_pi(ARGV[0].to_i)
end
puts "TIME: #{res} seconds"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.