开发者

When does (1.0/x)*x - 1.0 not evalute to 0.0?

I'm searching for an example when the expression

(1.0/x)*x - 1.0

does not evaluate to 0.0, assuming开发者_JAVA百科 that x is a double value in Java.

I'm also interested in a reason for that.


Some obvious examples include:

  • x = 0.0
  • x = Double.NaN
  • x = Double.POSITIVE_INFINITY
  • x = Double.NEGATIVE_INFINITY

Less obvious examples:

  • x = 0x1p-1050 (a denormalized double)
  • x = -1.0 / Double.POSITIVE_INFINITY (negative zero)

There may be examples where there occurs loss of precision, but I am yet to find one.


Here's a program that will list all values for which this is the case.

public static final void main(String[] args){
    for(long i=Long.MIN_VALUE; i<Long.MAX_VALUE; i++){
        double d = Double.longBitsToDouble(i);
        if(0.0d != (1.0d/d)*d - 1.0d){
            System.out.println(d);
        }
    }
}

Turns out there's lots and lots and lots of them - the program starts with a large range of denormalized numbers, and it's the case for all of them.

To get numbers in a more familiar range:

public static final void main(String[] args){
    for(long i=Double.doubleToLongBits(1.0d); i<Long.MAX_VALUE; i++){
        double d = Double.longBitsToDouble(i);
        if(0.0d != (1.0d/d)*d - 1.0d){
            System.out.println(d);
        }
    }
}

Still lots and lots of hits.

The reason? double has limited precision, and therefore it's fundamentally unable to represent all numbers. If your calculation has an intermediate result that cannot be exactly represented by double, your algebraic equalities cannot be expected to hold.


double x = 0.2300000000000001;
System.out.println((1.0/x)*x - 1.0);

Floating point loses precision.


x == 0

Because 0*infinity is undefined in maths.


I would try x = square root of 2 as it is none rational number and cannot be expressed as floating. for all who suggests x == 0, this is illegal equation. he is searching for a leagal value.

found an example, x = Math.sin(4.0).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜