Last active
August 29, 2015 14:19
-
-
Save komasaru/a091c46595cdbc8d276a to your computer and use it in GitHub Desktop.
Ruby script to compute pi with BBP formula.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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