Java – what happens when l (long) – = f (float)?

See English answers > floating point arithmetic not producing exact results 7

public class SimplePrint {

public static void main(String[] args) {
    long i = System.currentTimeMillis();
    System.out.println(i);
    float h = 0.0f;
    i -= h;
    System.out.println(i);
  }
}

The output is:

one trillion and four hundred and seventy-seven billion nine hundred and four million six hundred and thirty-six thousand nine hundred and two

one trillion and four hundred and seventy-seven billion nine hundred and four million six hundred and ninety-five thousand two hundred and ninety-six

But when I change the data type of the H variable

public class SimplePrint {

public static void main(String[] args) {
    long i = System.currentTimeMillis();
    System.out.println(i);
    double h = 0.0f;
    i -= h;
    System.out.println(i);
  }
}

Output changed:

one trillion and four hundred and seventy-seven billion nine hundred and four million six hundred and seventy-seven thousand five hundred and thirteen

one trillion and four hundred and seventy-seven billion nine hundred and four million six hundred and seventy-seven thousand five hundred and thirteen

Why is that so???

Solution

Such as JLS sec 15.26 2, the compound assignment operator E1 OP = E2 is equivalent to

E1 = (T) ((E1) op (E2))

Where t is the type of E1

So what you do in the first case is:

i = (long) (i - 0.0f)

In order to evaluate –, I have to be converted to floating point numbers, such as JLS sec 15.18 2. Description:

And 5.6 2:

The problem is that the value of I cannot be accurately expressed as float: because float has only 24 significant digits (see here), it can only accurately represent the value of about 2 ^ 24 (= 16777216); But the current millisecond time (at least on my machine) is about 147790541000, which is larger

Therefore, precision is lost when converting to float and cannot be restored when converting to long

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>