flo*_*her 2 ruby floating-point floating-accuracy
这里有什么不对?(ruby版本:1.9.2p290(2011-07-09修订版32553)[x86_64-darwin11.0.0]
x = 523.8
w = 46.9
xm = x + w
assert_equal w, (xm - x) # FAILS with: <46.9> expected but was <46.89999999999998>
Run Code Online (Sandbox Code Playgroud)
这是完全正常的; 这是关于浮点运算的低级概念而不是Ruby的事实,因此可以在任何语言中出现.
浮点运算不精确.平等应该用接近的线来代替 assert((xm-x).abs < epsilon)
,其中epsilon
有一些小的数字0.01
.