Skip to content

Instantly share code, notes, and snippets.

@timothypage
Created August 2, 2016 21:14
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 timothypage/7adeacd046af38d2c287d68b702d8a15 to your computer and use it in GitHub Desktop.
Save timothypage/7adeacd046af38d2c287d68b702d8a15 to your computer and use it in GitHub Desktop.
Gauss–Legendre algorithm
require 'pry'
# implements https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm
def calculate_pi(iterations)
a = 1.0
b = 1 / Math::sqrt(2)
t = 1.0 / 4
p = 1.0
while iterations > 0
a_next = ( a + b ) / 2.0
b_next = Math::sqrt( a * b )
t_next = t - p * ( a - a_next ) ** 2
p_next = 2 * p
a = a_next
b = b_next
t = t_next
p = p_next
iterations -= 1
end
pi = ( (a_next + b_next) ** 2 ) / ( 4 * t_next )
pi
end
binding.pry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment