Erlang 的精度
下一个代码在结果中给出了 5.999999999999998,但正确答案是 6。
Alpha = math:acos((4*4 + 5*5 - 3*3) / (2*4*5))
Area = 1/2 * 4 * 5 * math:sin(Alpha)
是否有可能得到 6?
Next code gives me 5.999999999999998 in Result, but right answer is 6.
Alpha = math:acos((4*4 + 5*5 - 3*3) / (2*4*5))
Area = 1/2 * 4 * 5 * math:sin(Alpha)
Is it possible to get 6?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您遇到了一个非常常见的问题,它有自己的网站,每个程序员都应该了解浮点运算。该问题是由于浮点运算在市场上几乎所有支持 FP 运算的 CPU 中的工作方式造成的。它不是 Erlang 特有的。
如果常规浮点算术不能满足您所需的精度或准确度,您可以使用任意精度算术库来代替内置算术。也许最著名的此类库是 GMP,但您必须将其包装在 NIF 从 Erlang 使用它。
有 至少一种纯 Erlang 替代品,但我没有这方面的经验,所以我不能个人赞同。
You have run into a problem so common that it has its own web site, What Every Programmer Should Know About Floating-Point Arithmetic. The problem is due to the way floating-point arithmetic works in pretty much every CPU on the market that supports FP arithmetic; it is not specific to Erlang.
If regular floating point arithmetic does not give you the precision or accuracy you need, you can use an arbitrary precision arithmetic library instead of the built-in arithmetic. Perhaps the most well-known such library is GMP, but you'd have to wrap it in NIFs to use it from Erlang.
There is at least one pure-Erlang alternative, but I have no experience with it, so I cannot personally endorse it.
计算是在硬件上使用标准浮点算法完成的。有时会出现舍入错误。
您真的需要 15 位精度吗?
要获得更“精确”的值,有多种选择:
或者您可以舍入到某个精度
。如果目的是打印该值,则使用浮点数的默认输出进行打印会降低精度。
或具有特定精度的
HTH
The calculation is done using standard floating point arithmetic on your hardware. Sometimes rounding errors show up.
Do you really need 15 digits of precision?
To get a more "exact" value there are multiple options:
or you could round to some precision
If the purpose is to print the value, then printing with the default output for floats give you less precision.
or with a specific precision
HTH