Given double values:

double a
double b
b < a

if:

double c = a - b;
double d = c + b

then does double number guarantee that:

d == a ?

Example:

double c = 20.0d - 2.0d;
double d = c + 2.0d;

is it true that d will be again equal to 20.0d? So in general I am asking if I substract and add the same double would it be still the same value ? This is only one case where a=20.0d and b= 2.0d. I need to be sure for this for every double value.

I tried with such example:

double s = 4.8d;
System.out.print(s + "\n");
s -= 0.4d;
System.out.print(s + "\n");
s += 0.4d;
System.out.print(s + "\n");

For this example the result matched my expectations:

4.8
4.3999999999999995
4.8

So this is what I need.

Thanks.

有帮助吗?

解决方案

Although this will work for 20 and 2, it is definitely not going to work in general: it will break for double values when the addition forces an increment of the exponent portion of the representation: the result will lose some precision.

Here is a simple example (in Java) illustrating the point:

double a = 1.0 / 3;
double b = 0.5;
double c = a + b;
double d = c - b;
System.out.println(a);
System.out.println(d);
System.out.println(a == d);

When you run it, this example prints the following:

0.3333333333333333
0.33333333333333326
false

The results become even more pronounced when the exponents of the values being added are different. For example, if you change b's value from 0.5 to 100000, the difference would be a lot bigger:

0.3333333333333333
0.3333333333284827
false

Changing b to 1E15 gives

0.3333333333333333
0.375
false

Changing b to 1E20 makes even the traces of the original a disappear:

0.3333333333333333
0.0
false

其他提示

Not necessarily. For example:

> a=1.1; b=10; (a-b) + b
1.0999999999999996
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top