减去数字时的奇怪行为

时间:2013-07-05 11:52:05

标签: javascript floating-point applescript

当我在Applescript(或其他语言)中使用此代码时:

set var1 to "0.00"
set var2 to "50.86"
set var3 to "1335.56"
set var4 to "60.72"
set netto to "1447.14"

set sub_totaal to var1 + var2 + var3 + var4
set sub_dif to sub_totaal - netto

答案是:-2.27373675443232E-13

为什么?

2 个答案:

答案 0 :(得分:0)

并非所有小数十进制值都具有精确(基数为2)的二进制表示。大多数编程语言都有义务遵守主机的浮点算术实现,这意味着交换和关联算法的常规规则不成立。

请注意,即使最终的十进制值:1447.14也不能将完全表示为(IEEE-754)浮点值。

无论您使用何种语言,了解这些限制至关重要。浮点精度/范围误差的分析本身几乎是一个单独的领域。

答案 1 :(得分:0)

嗯,要进行精确数学运算,您可以使用unix工具。例如,一个这样的工具是“bc”。所以只需将计算结果发送到命令行工具。

set var1 to "0.00"
set var2 to "50.86"
set var3 to "1335.56"
set var4 to "60.72"
set netto to "1447.14"

set cmd to var1 & "+" & var2 & "+" & var3 & "+" & var4
set sub_total to do shell script "echo " & quoted form of cmd & " | bc"

set cmd to sub_total & "-" & netto
set sub_dif to do shell script "echo " & quoted form of cmd & " | bc"

return {sub_total, sub_dif} --{"1447.14", "0"}