1

I'm simply trying to calculate percentage_imp, but instead of 0.22 (exactly 0.22, no rounding error), I get 0.22000000000000003!! I used to get similar odd results, and I've been told to move from float to double, but this one is still odd! All the variables below are double!

double percentage_imp= budget -  (sum_minlessi)/ (sum_i + sum_lessi);
4

3 回答 3

3

Thats because of the floating point precision values.

You must read:- What Every Computer Scientist Should Know About Floating-Point Arithmetic

You must also read how floating point arithmetic and its internal representation works.

于 2013-10-27T05:28:04.553 回答
1

0.22 is not representable as a double.

As an example, 1/3 cannot be represented in base-10, so we approximate with 0.3333333333333333.

于 2013-10-27T05:28:01.963 回答
0

Its a rounding error inherit in binary calculations. Not all rational decimal numbers can be represented as a single decimal number in binary. As such, when you perform operations such as multiply and divide, you'll get some nasty error on the last few digits.

Moving from double to float doesn't change this as double is simply a double precision floating point number.

I suggest you look at this link

As a extra bonus in java, simple operations such as binary multiplications are optimized as much as possible utilizing any sort of hardware optimizations when possible yielding different answers on different machines. If you require consistent behavior across all machines use the strictfp keyword in your class declaration.

于 2013-10-27T05:28:37.773 回答