Created
August 12, 2014 03:42
-
-
Save tkfm-yamaguchi/fe9c6f32c2be9cceb229 to your computer and use it in GitHub Desktop.
sqrt by newton method
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
# coding: utf-8 | |
# | |
# sqrt by newton method | |
# | |
def gen_sqrt_iter(square, seed=1) | |
Fiber.new do | |
f = ->(x){ x**2.0 - square } | |
fd = ->(x){ 2.0 * x } | |
xn = ->(x){ x - f[x]/fd[x] } | |
x = seed | |
loop do | |
Fiber.yield(x = xn[x]) | |
end | |
end | |
end | |
# main: sqrt of 2 | |
iter = gen_sqrt_iter(2) | |
10.times do | |
puts iter.resume | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment