Skip to content

Instantly share code, notes, and snippets.

@fetburner
Created March 23, 2024 14:28
Show Gist options
  • Save fetburner/ed9f57b4d91d0a921c6034f4770758bd to your computer and use it in GitHub Desktop.
Save fetburner/ed9f57b4d91d0a921c6034f4770758bd to your computer and use it in GitHub Desktop.
ラマヌジャンの公式で円周率を計算するプログラム
require "bigdecimal"
def formula(i, d)
return [
(1 - 4 * i) * (2 * i - 1) * (4 * i - 3),
24893568 * i * i * i * (21460 * i - 20337),
24893568 * i * i * i,
] if d <= 0
a0, b0, c0 = formula(2 * i - 1, d - 1)
a1, b1, c1 = formula(2 * i, d - 1)
[a0 * a1, a0 * b1 + b0 * c1, c0 * c1]
end
def pi(n)
_, x, y = formula(1, Math.log2(n).-(1.55849716603186539).ceil)
BigDecimal(3528 * y, n).div(x, n)
end
if $0 == __FILE__
if ARGV.size == 1
p pi(ARGV[0].to_i)
else
puts "TRY: ruby ramanujan.rb 1000"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment