fork download
  1. # 浮動小数点の誤差は考慮していない
  2. def f(u, v)
  3. return [0] if u <= 0
  4. seq = []
  5. loop do
  6. n = v.to_i
  7. return seq + [u.ceil] if n >= u.ceil
  8. seq << n
  9. u, v = 1 / (v - n), 1 / (u - n)
  10. end
  11. end
  12.  
  13. def g(x, y)
  14. a = x.to_f.abs
  15. seq = f(a - y, a + y)
  16. z = seq.pop.quo(1)
  17. z = seq.pop + 1.quo(z) while !seq.empty?
  18. z *= x < 0 ? -1 : 1
  19. puts "x=#{x}, y=#{y} -> #{z} = #{z.to_f}"
  20. end
  21.  
  22. g(0.02, 0.03)
  23. g(0.3, 0.1)
  24. g(0.5, 0.2)
  25. g(-0.3, 0.1)
  26. g(0.07, 0.02)
  27. g(0.0000000123, 0.0000000003)
  28. g(3.14159265358979, 0.00000000000001)
Success #stdin #stdout 0.02s 7412KB
stdin
Standard input is empty
stdout
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