朱莉娅:浮动总和是错误的?
我如何确保通过0.2在每次迭代时添加我得到正确的结果?
some = 0.0
for i in 1:10
some += 0.2
println(some)
end
上面的代码给了我
0.2
0.4
0.6000000000000001
0.8
1.0
1.2
1.4
1.5999999999999999
1.7999999999999998
1.9999999999999998
回答
浮点数只是近似正确,如果加起来为无穷大,误差将变得无穷大,但你仍然可以用它非常精确地计算。如果您需要评估结果并查看它是否正确,您可以使用isapprox(a,b)或a ? b。
IE
some = 0.
for i in 1:1000000
some += 0.2
end
isapprox(some, 1000000 * 0.2)
# true
否则,您可以在 for 循环中添加整数,然后除以 10。
some = 0.
for i in 1:10
some += 2.
println(some/10.)
end
#0.2
#0.4
#0.6
#0.8
#1.0
#1.2
#1.4
#1.6
#1.8
#2.0
有关使用浮点数进行计数的更多信息:https :
//en.wikipedia.org/wiki/Floating-point_arithmetic
- Option three: use fractions. `some = 0//1`, `some += 1//5`.