Skip to content

Instantly share code, notes, and snippets.

@tkfm-yamaguchi
Created August 12, 2014 03:42
Show Gist options
  • Save tkfm-yamaguchi/fe9c6f32c2be9cceb229 to your computer and use it in GitHub Desktop.
Save tkfm-yamaguchi/fe9c6f32c2be9cceb229 to your computer and use it in GitHub Desktop.
sqrt by newton method
# 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