Java technology -6- floating point calculation

Different floating-point operations and integer operations are: bit floating-point number can not shift operation and; the same numerical operations like addition, subtraction and integer arithmetic;

Although large floating point number stored value range, but saved floating-point value is not accurate.

public  class the Main {
     public  static  void main (String [] args) {
         Double x = 1.0 / 10 ;
         Double y. 1 = - 9.0 / 10 ;
         // see if x and y are equal: 
        System.out.println (x); 
        the System .out.println (Y); 
    } 
}

Floating point computation errors due to the presence, the two floating-point equality comparison is often erroneous results may occur. Comparison method is to determine the correct absolute value of difference of two floating-point numbers is less than a very small number:

// compare x and y are equal, the absolute value of the first difference calculated: 
Double R & lt the Math.abs = (x - y);
 // then determines whether the absolute value is small enough: 
IF (R & lt <0.00001 ) {
     // may be considered is equal to 
} the else {
     // unequal 
}

Type promotion

If the two numbers involved in operations in which a is an integer, then the integer can be automatically promoted to float:

public class Main {
    public static void main(String[] args) {
        int n = 5;
        double d = 1.2 + 24.0 / n; // 6.0
        System.out.println(d);
    }
}
Pay special attention, in a complex of four operations, the automatic upgrade of two integer arithmetic does not appear. For example: 

Double D 24 = + 1.2 /. 5; // 5.2

Evaluates to 5.2, because the compiler calculates 24/5 subexpression, according calculates two integers, the result remains an integer of 4.

overflow

Divisor in integer arithmetic for the 0time being given, and floating-point operations in the divisor 0, the error will not, but will return several special values:

  • NaNIt represents Not a Number
  • InfinityRepresent infinity
  • -InfinityRepresenting negative infinity

Casts

To float casts an integer. When the transformation, floating-point fractional part will be lost. If the transition exceeds the maximum range of integers can be represented, it will return to the maximum integer.

int n1 = (int) 12.3; // 12
int n2 = (int) 12.7; // 12
int n2 = (int) -12.7; // 12
int n3 = (int) (12.7 + 0.5); // 13
int n4 = (int) 1.2e20; // 2147483647

If you want rounding, you can add another 0.5 casts to a float:

public class Main {
    public static void main(String[] args) {
        double d = 2.6;
        int n = (int) (d + 0.5);
        System.out.println(n);
    }
}

 

Guess you like

Origin www.cnblogs.com/delongzhang/p/11260100.html