In Java why number operations' result is different from variable operations

peterboston :

I have the following code:

System.out.println("(int) (10 * 0.75 / 0.6 + 0.5)=" + (int) (10 * 0.75 / 0.6 + 0.5));

The print out is: (10 * 0.75 / 0.6 + 0.5)=13

and another one:

int a = 10;
float b = 0.75f;
float c = 0.6f;
System.out.println("(int) (a * b / c + 0.5)=" + (int) (a * b / c + 0.5));

The print out is (a * b / c + 0.5)=12

Why they are different?

EDIT:

System.out.println("(int) (10 * 0.75f / 0.6f + 0.5f)=" + (int) (10 * 0.75f / 0.6f + 0.5f));

The print out is 12 now: (int) (10 * 0.75f / 0.6f + 0.5f)=12

knittl :

Your variables are assigned the float values 0.75f and 0.6f, your inline expression uses the double values 0.75 and 0.6.

You will get the same result if you use the same types for your values, so either 0.…f in your inline expression or making your variables double values.

Doubles can store 64 bits (1 sign bit, 11 bits exponent and 53 bits significand) of precision, floats or Singles only 32 bits (1 sign bit, 8 bits exponent and 24 bits significand). The difference in the result is explained by rounding errors.

Read up on how floating point numbers are stored in a Computer on Wikipedia:

Double-precision binary floating-point is a commonly used format on PCs, due to its wider range over single-precision floating point, in spite of its performance and bandwidth cost. As with single-precision floating-point format, it lacks precision on integer numbers when compared with an integer format of the same size. It is commonly known simply as double. The IEEE 754 standard specifies a binary64 as having:

Sign bit: 1 bit
  Exponent: 11 bits
  Significand precision: 53 bits (52 explicitly stored)

The sign bit determines the sign of the number (including when this number is zero, which is signed).

The exponent field can be interpreted as either an 11-bit signed integer from −1024 to 1023 (2's complement) or an 11-bit unsigned integer from 0 to 2047, which is the accepted biased form in the IEEE 754 binary64 definition. If the unsigned integer format is used, the exponent value used in the arithmetic is the exponent shifted by a bias – for the IEEE 754 binary64 case, an exponent value of 1023 represents the actual zero (i.e. for 2e − 1023 to be one, e must be 1023). Exponents range from −1022 to +1023 because exponents of −1023 (all 0s) and +1024 (all 1s) are reserved for special numbers.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=32343&siteId=1