用C部门的奇怪结果 [英] Strange result of division in C

查看:97
本文介绍了用C部门的奇怪结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些重复:

   1.265 * 10000 = 126499.99999999999 ?????

  如何存储浮点?当有什么关系?

  <一href=\"http://stackoverflow.com/questions/327544/strange-floating-point-behaviour-in-a-java-program\">Strange在Java程序中
  <一href=\"http://stackoverflow.com/questions/177506/why-do-i-see-a-double-variable-initialized-to-some-value-like-214-as-2139999961\">Why我会看到初始化像某些21.4值的双变量作为21.399999618530273?

  在Flash此外错误

我除以40(23/40),23。在C这种操作导致0.5749999999999996。但实际上它必须是0.575!

I divide 23 by 40 (23/40). In C this operation results in 0.5749999999999996. But actually it must be 0.575!

我该如何解决这个问题?

How can I fix this?

推荐答案

现在的问题是,因为0.575值没有在浮点编码一个确切的再presentation。此修复程序取决于你与价值,以及不准确造成的影响做什么。

The problem is because the .575 value doesn't have an exact representation in floating point encoding. The fix depends on what you have to do with the value as well as the impact of the inaccuracy.

如果它只是一个显示问题使用四舍五入到3位小数,你会得到0.575。

If it is just a display problem use rounding to 3 decimals and you'll get the 0.575.

如果是因为计算误差,尽量保持价值,这将是准确的一小部分。你必须来存储和处理两个浮点数值,但它是准确的。推迟有效分工到最后时刻,当你需要的结果。

If it is because of computation inaccuracy, try keeping the value as a fraction which will be exact. You'll have to store and handle two floating point values but it will be exact. Postpone the effective division to the last moment when you need the result.

检查两个值之间的差是相关的问题。例如减法开方小量的值,并检查变化多大影响最终计算结果,并将其与所需的或所希望的precision比较

Check if the difference between the two value is relevant for your problem. For instance subtract sqrt epsilon to the value and check how much the change influences the final computation result and compare it with the required or desired precision.

不幸的是我们不得不忍受再浮法presentation真正的价值的局限性。使用128位precision花车将会使误差更小,但不为null。

Unfortunately we have to live with the limitation of real value representation in float. Using 128 bit precision floats will make the error much smaller but not null.

这篇关于用C部门的奇怪结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆