双重计算产生奇数结果 [英] Double calculation producing odd result
问题描述
哦,我喜欢这些...这些都是由于双重表示的不准确造成的,而浮点运算就是这些。它通常由二进制中的循环数(即基本2浮点表示)引起。例如,十进制1/3 = 0.3333'在二进制1/10中是一个循环数,这意味着它不能被完美地表示。尝试这样:1 - 0.1 - 0.1 - 0.1 - 0.1。你不会得到0.6: - )
为了解决这个问题,请使用BigDecimal(首选)或者通过首先将其乘以10000来操纵double,然后将其舍入,然后将其分割再次(较不干净)。
好的问题...过去造成了巨大的问题。导弹超越目标,发射后的卫星坠毁等等。在网上搜索一些,你会惊奇的!
I have 2 numbers stored as Double, 1.4300 and 1.4350. When I subtract 1.4350 - 1.4300, it gives me the result: 0.0050000000000001155. Why does it add 1155 to the end and how can I solve this so that it returns 0.005 or 0.0050? I'm not sure rounding will work as I'm working with 2 and 4 decimal numbers.
Oh, I love these... these are caused by inaccuracy in the double representation and floating-point arithmetic is full of these. It is often caused by recurring numbers in binary (i.e. base-2 floating-point representation). For example, in decimal 1/3 = 0.3333' In binary 1/10 is a recurring number, which means it cannot be perfectly represented. Try this: 1 - 0.1 - 0.1 - 0.1 - 0.1. You wont get 0.6 :-)
To solve this, use BigDecimal (preferred) or manipulating the double by first multiplying it something like 10000, then rounding it and then dividing it again (less clean).
Good question... it has caused huge problems in the past. Missiles overshooting targets, satellites crashing after launch, etc. Search the web for some, you'll be amazed!
这篇关于双重计算产生奇数结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!