Skip to content

Instantly share code, notes, and snippets.

@46bit
Created April 17, 2011 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 46bit/924615 to your computer and use it in GitHub Desktop.
Save 46bit/924615 to your computer and use it in GitHub Desktop.
A simple Ruby script to calculate using the Chudnovsky algorithm. Seems to only be accurate to 69 d.p. according to http://www.angio.net/pi/bigpi.cgi - likely an issue with the 10005^0.5 precision and perhaps some proper floating point errors?
#!/usr/bin/env ruby
require 'bigdecimal';
class Integer
def factorial
f = 1; for i in 1..self; f *= i; end; f
end
end
iterations = 500;
multIPi = BigDecimal.new("0");
for k in (0..iterations)
multIPi +=
(
BigDecimal.new((6*k).factorial.to_s) *
BigDecimal.new((13591409 + 545140134 * k).to_s)
) /
(
BigDecimal.new((3*k).factorial.to_s) *
BigDecimal.new(k.factorial.to_s)**3 *
BigDecimal.new(((-640320)**(3*k)).to_s)
);
end
pi = BigDecimal.new("426880") * BigDecimal.new("10005").sqrt(iterations * 200) / multIPi;
puts pi.to_s("F")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment