浮点精度误差 [英] Floating Point Precision Error
问题描述
我对下面的LISP表达式有疑问。
I am having problem with the LISP expression below. There is floating precision error while doing sum for floating point numbers.
CL-USER> (+ -380 -158.27 -35.52)
Actual: -573.79004
Expected: -573.79000
请建议我如何在LISP(我正在使用Lispworks)中达到预期的结果。
Please suggest me how can I achieve the expected result in LISP (I am using Lispworks).
推荐答案
< h1>浮点数不精确
浮点数是具有一定精度的数学实数的子集,它们是不是 精确数字。四舍五入的错误是不可避免的。
Floats are not exact
Floats represent a subset of mathematical reals with certain precision, they are not exact numbers. Round off errors are inevitable.
ANSI Common Lisp标准为 4(!)级浮点精度:short,single,double,long (所有实现均提供至少2个)。两者都不是确切的,但是ORACLE可能正在使用 double
,因此,如果坚持使用double,就可以了。
The ANSI Common Lisp standard provides for 4(!) levels of float precision: short, single, double, long (all implementations provide at least 2). Neither is exact, but ORACLE is probably using double
, so if you stick with doubles, you should be fine.
如果要进行精确计算,则应使用 整数
(例如,以美分而不是美元表示货币)或 比率
s。
If you want to do exact computations, you should be using integer
s (e.g., representing currency as a number of cents, not dollars) or ratio
s.
这篇关于浮点精度误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!