Strange result of division in C [duplicate]

2019-01-20 16:39发布

6条回答
forever°为你锁心
2楼-- · 2019-01-20 17:09

Take a look at this - it should tell you everything you need to know about Why Computers Suck At Math

查看更多
ら.Afraid
3楼-- · 2019-01-20 17:13

It is normal with floating point arithmetic. You can change the way how your floats and doubles are printed using %.3g for example

查看更多
来,给爷笑一个
4楼-- · 2019-01-20 17:15

You can't fix this. Not all numbers can be represented as floats, see "how is floating point stored, when does it matter".

查看更多
小情绪 Triste *
5楼-- · 2019-01-20 17:16

That is an artifact from how floating point numbers are stored.

Either you could round the answer sprintf("%.3f", result) or use some Decimal handling package.

查看更多
成全新的幸福
6楼-- · 2019-01-20 17:17

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.

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.

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.

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.

查看更多
Viruses.
7楼-- · 2019-01-20 17:17

I suggest you do a search on the web for "floating point accuracy" or look at the absolute dozens of other questions on SO that yours is a duplicate of.

查看更多
登录 后发表回答