Created
August 2, 2016 21:14
-
-
Save timothypage/7adeacd046af38d2c287d68b702d8a15 to your computer and use it in GitHub Desktop.
Gauss–Legendre algorithm
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
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