本文簡要介紹ruby語言中 Float.next_float
的用法。
用法
next_float → float
返回 next-larger 可表示的浮點數。
這些示例顯示了每個浮點 f
和相應的 f.next_float
的內部存儲值(64 位十六進製):
f = 0.0 # 0x0000000000000000
f.next_float # 0x0000000000000001
f = 0.01 # 0x3f847ae147ae147b
f.next_float # 0x3f847ae147ae147c
在此處的其餘示例中,輸出以通常的方式顯示(結果 to_s
):
0.01.next_float # => 0.010000000000000002
1.0.next_float # => 1.0000000000000002
100.0.next_float # => 100.00000000000001
f = 0.01
(0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.next_float }
輸出:
0 0x1.47ae147ae147bp-7 0.01 1 0x1.47ae147ae147cp-7 0.010000000000000002 2 0x1.47ae147ae147dp-7 0.010000000000000004 3 0x1.47ae147ae147ep-7 0.010000000000000005 f = 0.0; 100.times { f += 0.1 } f # => 9.99999999999998 # should be 10.0 in the ideal world. 10-f # => 1.9539925233402755e-14 # the floating point error. 10.0.next_float-10 # => 1.7763568394002505e-15 # 1 ulp (unit in the last place). (10-f)/(10.0.next_float-10) # => 11.0 # the error is 11 ulp. (10-f)/(10*Float::EPSILON) # => 8.8 # approximation of the above. "%a" % 10 # => "0x1.4p+3" "%a" % f # => "0x1.3fffffffffff5p+3" # the last hex digit is 5. 16 - 5 = 11 ulp.
相關: Float#prev_float
相關用法
- Ruby Float.numerator用法及代碼示例
- Ruby Float.nan?用法及代碼示例
- Ruby Float.self - other用法及代碼示例
- Ruby Float.rationalize用法及代碼示例
- Ruby Float.truncate用法及代碼示例
- Ruby Float.quo用法及代碼示例
- Ruby Float.finite?用法及代碼示例
- Ruby Float.self / other用法及代碼示例
- Ruby Float.coerce用法及代碼示例
- Ruby Float.self < other用法及代碼示例
- Ruby Float.to_int用法及代碼示例
- Ruby Float.self % other用法及代碼示例
- Ruby Float.self >用法及代碼示例
- Ruby Float.fdiv用法及代碼示例
- Ruby Float.eql?用法及代碼示例
- Ruby Float.to_d用法及代碼示例
- Ruby Float.to_i用法及代碼示例
- Ruby Float.self + other用法及代碼示例
- Ruby Float.self >=用法及代碼示例
- Ruby Float.self ** other用法及代碼示例
- Ruby Float.modulo用法及代碼示例
- Ruby Float.self ==用法及代碼示例
- Ruby Float.self * other用法及代碼示例
- Ruby Float.abs用法及代碼示例
- Ruby Float.self <=>用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Float.next_float。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。