# 浮動小数点の誤差は考慮していない
def f(u, v)
return [0] if u <= 0
seq = []
loop do
n = v.to_i
return seq + [u.ceil] if n >= u.ceil
seq << n
u, v = 1 / (v - n), 1 / (u - n)
end
end
def g(x, y)
a = x.to_f.abs
seq = f(a - y, a + y)
z = seq.pop.quo(1)
z = seq.pop + 1.quo(z) while !seq.empty?
z *= x < 0 ? -1 : 1
puts "x=#{x}, y=#{y} -> #{z} = #{z.to_f}"
end
g(0.02, 0.03)
g(0.3, 0.1)
g(0.5, 0.2)
g(-0.3, 0.1)
g(0.07, 0.02)
g(0.0000000123, 0.0000000003)
g(3.14159265358979, 0.00000000000001)
IyDmta7li5XlsI/mlbDngrnjga7oqqTlt67jga/ogIPmha7jgZfjgabjgYTjgarjgYQKZGVmIGYodSwgdikKCXJldHVybiBbMF0gaWYgdSA8PSAwCglzZXEgPSBbXQoJbG9vcCBkbwoJCW4gPSB2LnRvX2kKCQlyZXR1cm4gc2VxICsgW3UuY2VpbF0gaWYgbiA+PSB1LmNlaWwKCQlzZXEgPDwgbgoJCXUsIHYgPSAxIC8gKHYgLSBuKSwgMSAvICh1IC0gbikKCWVuZAplbmQKCmRlZiBnKHgsIHkpCglhID0geC50b19mLmFicwoJc2VxID0gZihhIC0geSwgYSArIHkpCgl6ID0gc2VxLnBvcC5xdW8oMSkKCXogPSBzZXEucG9wICsgMS5xdW8oeikgd2hpbGUgIXNlcS5lbXB0eT8KCXogKj0geCA8IDAgPyAtMSA6IDEKCXB1dHMgIng9I3t4fSwgeT0je3l9ICAtPiAgI3t6fSA9ICN7ei50b19mfSIKZW5kCgpnKDAuMDIsIDAuMDMpCmcoMC4zLCAwLjEpCmcoMC41LCAwLjIpCmcoLTAuMywgMC4xKQpnKDAuMDcsIDAuMDIpCmcoMC4wMDAwMDAwMTIzLCAwLjAwMDAwMDAwMDMpCmcoMy4xNDE1OTI2NTM1ODk3OSwgMC4wMDAwMDAwMDAwMDAwMSk=
x=0.02, y=0.03 -> 0/1 = 0.0
x=0.3, y=0.1 -> 1/3 = 0.3333333333333333
x=0.5, y=0.2 -> 1/2 = 0.5
x=-0.3, y=0.1 -> -1/3 = -0.3333333333333333
x=0.07, y=0.02 -> 1/12 = 0.08333333333333333
x=1.23e-08, y=3.0e-10 -> 1/79365080 = 1.2599999899200001e-08
x=3.14159265358979, y=1.0e-14 -> 53047102/16885417 = 3.141592653589781