简单金融计算中的数值精度
我在大学学过一门课程,解释了如何(除其他外)命令数学执行以最大限度地提高精度并降低有限精度环境中舍入误差的风险。
我们正在开发一个具有您通常的利息计算等功能的金融系统。有人可以分享/提醒我如何构建您的计算以最大限度地减少精度损失吗?
例如,我知道必须避免分裂。另外,在除法时,如果可能的话,先除最大的数。
I did a course at university that explained how (amongst other things) to order your mathematical execution to maximize precision and reduce the risk of rounding errors in a finite precision environment.
We are working on a financial system with your usual interest calculations and such. Can somebody please share/remind me how to structure your calculations as to minimze loss of precision?
I know that, for instance, division must be avoided. Also, when you divide, to divide the largest number first, if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
数值计算的基本规则是避免减去几乎相等的数。乘法和除法总是准确的:在执行乘法或除法时最多损失一位精度。但是,如果两个数字同意 n 位,则在它们的减法中最多可能会损失 n 位精度。
有各种各样的技巧可以避免这种减法。例如,假设您需要针对较小的 x 值计算 exp(x) - 1。 (这是您在利息计算中可能会做的事情。)如果 x 非常小,以至于 exp(x) 等于 1 到计算机的所有精度,则减法将精确地给出 0,并且产生的相对误差将为 100% 。但如果您使用泰勒近似 exp(x) - 1 = x + x^2/2 + ... 您可以获得更准确的答案。例如,exp(10^-17) - 1 将完全不准确,但 10^-17(一项泰勒近似)将非常准确。这就是
expm1
等函数的工作原理。参见log1p
和expm1
的解释这里。如果您担心数值准确性,则需要了解 浮点数剖析,以便了解什么是安全的、什么是不安全的。
The cardinal rule of numerical computing is to avoid subtracting nearly equal numbers. Multiplication and division are always accurate: you lose at most one bit of precision in performing a multiply or divide. But if two numbers agree to n bits, you can lose up to n bits of precision in their subtraction.
There are all kinds of tricks for avoiding such subtractions. For example, suppose you need to calculate exp(x) - 1 for small values of x. (This is something you might do in an interest calculation.) If x is so small that exp(x) equals 1 to all the precision of the computer, then the subtraction will give exactly 0, and the resulting relative error will be 100%. But if you use the Taylor approximation exp(x) - 1 = x + x^2/2 + ... you could get a more accurate answer. For example, exp(10^-17) - 1 will be completely inaccurate, but 10^-17, the one-term Taylor approximation, would be very accurate. This is how functions like
expm1
work. See the explanation oflog1p
andexpm1
here.If you're concerned about numerical accuracy, you need to understand the anatomy of floating point numbers in order to know what is safe and what is not.
使用美分金额,而不是美元。
Use amounts in cents, not dollars.
精度损失通常与浮点二进制表示的使用有关。金融系统不应使用此类表示形式,而应使用任意精度数字(例如 Java 中的 BigDecimal 和 .NET 中的decimal)。这应该是你的第一步。
Loss of precision is usually related to the use of floating point binary representations. A financial system should not use such representations and use arbitrary precision numbers instead (Such as BigDecimal in Java and decimal in .NET). That should be your first move.
还可以使用区间算术
There is also the possibility to employ Interval Arithmetic