Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

1. Math class and StrictMath class

  • Math class: Contains methods for performing basic numerical operations such as exponents, logarithms, square roots, and trigonometric functions. Unlike some numerical methods of the StrictMath class, all implementations of the equivalent functions of the Math class are not defined to return bitwise identical results. This relaxation allows for better implementation without the need for strict reproducibility.

  • StrictMath class: contains methods for performing basic numerical operations such as exponential functions, logarithmic functions, square root functions, and trigonometric functions.

2. Common method classes

  • Trig sine; cos; tan; cot; And his inverse trigonometric functions (I share the source of a trigonometric function)

Math calls StrictMath’s sin method, but there is no logic in the StrictMath method. A native method is A Java method whose implementation is provided by non-Java code. Therefore, there is no method body when defining a native method. For the analysis of the characteristics of native method, you can check this article (I think it is well written through online search).

  • Square root cube root SQRT CBRT
public static double sqrt(double a) {
    return StrictMath.sqrt(a); 
    
StrictMathç±»
public static native double sqrt(double a);
Copy the code
  • Pow of a, b, a to the b

  • Calculate the maximum and minimum values Max min

public static int max(int a, int b) {
    return (a >= b) ? a : b;
}
Copy the code
  • Round round
public static int round(float a) {
    int intBits = Float.floatToRawIntBits(a);
    int biasedExp = (intBits & FloatConsts.EXP_BIT_MASK)
            >> (FloatConsts.SIGNIFICAND_WIDTH - 1);
    int shift = (FloatConsts.SIGNIFICAND_WIDTH - 2
            + FloatConsts.EXP_BIAS) - biasedExp;
    if ((shift & -32) == 0) { // shift >= 0 && shift < 32
        // a is a finite number such that pow(2,-32) <= ulp(a) < 1
        int r = ((intBits & FloatConsts.SIGNIF_BIT_MASK)
                | (FloatConsts.SIGNIF_BIT_MASK + 1));
        if (intBits < 0) {
            r = -r;
        }
        return ((r >> shift) + 1) >> 1;
    } else {
        return (int) a;
    }
}
Copy the code
  • Random number
private static final class RandomNumberGeneratorHolder {
    static final Random randomNumberGenerator = new Random();
}

public static double random() {
    return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
}
Copy the code

The Random class that we usually use calls nextDouble for Random numbers greater than or equal to 0.0 and less than or equal to 1.0