Math类中常用的方法

503 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动

1. Math类和StrictMath类

  • Math类: 包含用于执行基本数值运算的方法,如初等指数、对数、平方根和三角函数,与StrictMath类的某些数值方法不同,Math类的等效函数的所有实现都没有定义为返回逐位相同的结果。这种放宽允许在不需要严格再现性的情况下更好地执行实施。

  • StrictMath类:包含用于执行基本数值运算的方法,如初等指数函数、对数函数、平方根函数和三角函数。

2.常用的方法类

  • 三角函数 sin; cos;tan;cot;以及他的反三角函数 (我分享一个三角函数的源码)

image.png

image.png

去看源码发现,Math调用的是StrictMath类的sin方法,但去看见方法里没有任何逻辑实现,但这个关键字值得我们去探索一下就是native native方法:即java调用非java代码的接口(A native method is a Java method whose implementation is provided by non-java code.),所以再定义一个native方法时就没有方法体,关于native方法具有的分分析,可以查看下这篇文章(通过网上搜索觉得这篇写的比较好)

  • 平方根 立方根 sqrt cbrt
public static double sqrt(double a) {
    return StrictMath.sqrt(a); 
    
StrictMath类
public static native double sqrt(double a);
  • 计算次方 pow(a, b) 计算a的b次方

  • 计算最大最小值 max min

public static int max(int a, int b) {
    return (a >= b) ? a : b;
}
  • 四舍五入 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;
    }
}
  • 取随机数 random
private static final class RandomNumberGeneratorHolder {
    static final Random randomNumberGenerator = new Random();
}

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

其实可以发现 就是我们平常使用的Random类封装后 看这个调用的是nextDouble大于或者等于0.0小于不等于1.0的随机数