一、Math函数

Math函数集成了大量的数学方法,这是Java编程中不可缺少的一个库函数。下面我将从源码角度出发详细的介绍Math函数内部集成的一些方法。

二、math函数方法

首先math库进行了一个无参构造方法

private Math() {}

math库首先定义了两个常量一个e和一个π。

public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;

定义次方越界

static double twoToTheDoubleScaleUp = powerOfTwoD(512);
    static double twoToTheDoubleScaleDown = powerOfTwoD(-512);

定义负零浮点位和负零双精度位

private static long negativeZeroFloatBits  = Float.floatToRawIntBits(-0.0f);
private static long negativeZeroDoubleBits = Double.doubleToRawLongBits(-0.0d);

下面函数主要实现sin函数的计算,传入的参数为弧度值

public static double sin(double a) {
        return StrictMath.sin(a); // default impl. delegates to StrictMath
    }

下面函数主要实现cos函数的计算,传入的参数为弧度值

public static double cos(double a) {
        return StrictMath.cos(a); // default impl. delegates to StrictMath
    }

下面函数主要实现tan函数的计算,传入的参数为弧度值

public static double tan(double a) {
        return StrictMath.tan(a); // default impl. delegates to StrictMath
    }

下面函数主要实现arcsin函数的计算

public static double asin(double a) {
        return StrictMath.asin(a);
   }

下面函数主要实现arccos函数的计算

public static double acos(double a) {
        return StrictMath.acos(a); // default impl. delegates to StrictMath
    }

下面函数主要实现arctan函数的计算

public static double atan(double a) {
        return StrictMath.atan(a); // default impl. delegates to StrictMath
    }

下面函数将角度值转换为弧度值

public static double toRadians(double angdeg) {
        return angdeg / 180.0 * PI;
    }

下面函数是将弧度值转化为角度值

public static double toDegrees(double angrad) {
        return angrad * 180.0 / PI;
    }

返回欧拉的a次方

public static double exp(double a) {
        return StrictMath.exp(a);
    }

返回log2 a的值

public static double log(double a) {
        return StrictMath.log(a); // default impl. delegates to StrictMath
    }

返回log10 a的值

public static double log10(double a) {
        return StrictMath.log10(a); // default impl. delegates to StrictMath
    }

返回a的开方

public static double sqrt(double a) {
        return StrictMath.sqrt(a); 
    }

返回a的立方根

public static double cbrt(double a) {
        return StrictMath.cbrt(a);
    }

按照 IEEE 754 标准的规定计算两个参数的余数运算。余数在数学上等于 f1 - f2 × n,其中 n 是最接近商 f1f2 的精确数学值的数学整数,如果两个数学整数同样接近 f1f2,则 n 是偶数整数。如果余数为零,则其符号与第一个参数的符号相同。

public static double IEEEremainder(double f1, double f2) {
        return StrictMath.IEEEremainder(f1, f2); 
    }

向上取整

public static double ceil(double a) {
        return StrictMath.ceil(a); 
    }

向下取整

public static double floor(double a) {
        return StrictMath.floor(a); 
    }

返回值与参数最接近且等于数学整数的双精度值。如果作为数学整数的两个 double 值同样接近,则结果是偶数的整数值

public static double rint(double a) {
        return StrictMath.rint(a); // default impl. delegates to StrictMath
    }

从直角坐标 (x, y) 到极坐标 (r, theta) 的转换返回角度 theta。此方法通过计算 yx 在 -pi 到 pi 范围内的反正切来计算相位 theta。

public static double atan2(double y, double x) {
        return StrictMath.atan2(y, x); // default impl. delegates to StrictMath
    }

返回a的b次方

public static double pow(double a, double b) {
        return StrictMath.pow(a, b);
    }

返回与参数最接近的整数,关系四舍五入为正无穷大。

ublic 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
            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;
        }
    }

返回与参数最接近的长整数,关系四舍五入为正无穷大。

public static long round(double a) {
        long longBits = Double.doubleToRawLongBits(a);
        long biasedExp = (longBits & DoubleConsts.EXP_BIT_MASK)
                >> (DoubleConsts.SIGNIFICAND_WIDTH - 1);
        long shift = (DoubleConsts.SIGNIFICAND_WIDTH - 2
                + DoubleConsts.EXP_BIAS) - biasedExp;
        if ((shift & -64) == 0) { 
            long r = ((longBits & DoubleConsts.SIGNIF_BIT_MASK)
                    | (DoubleConsts.SIGNIF_BIT_MASK + 1));
            if (longBits < 0) {
                r = -r;
            }
            return ((r >> shift) + 1) >> 1;
        } else {
            return (long) a;
        }
    }

定义随机数生成器

private static final class RandomNumberGeneratorHolder {
        static final Random randomNumberGenerator = new Random();
    }

返回带正号的双精度值,大于或等于 0.0 且小于 1.0。返回值是伪随机选择的,具有该范围内的(近似)均匀分布。

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

返回其参数的总和,如果结果溢出 int 则抛出异常。

public static int addExact(int x, int y) {
        int r = x + y;
        // HD 2-12 Overflow iff both arguments have the opposite sign of the result
        if (((x ^ r) & (y ^ r)) < 0) {
            throw new ArithmeticException("integer overflow");
        }
        return r;
    }

返回其参数的总和,如果结果溢出 long 则抛出异常。

public static long addExact(long x, long y) {
        long r = x + y;
        // HD 2-12 Overflow iff both arguments have the opposite sign of the result
        if (((x ^ r) & (y ^ r)) < 0) {
            throw new ArithmeticException("long overflow");
        }
        return r;
    }

返回x和y的差值,超过int就抛出异常

public static int subtractExact(int x, int y) {
        int r = x - y;
        // HD 2-12 Overflow iff the arguments have different signs and
        // the sign of the result is different than the sign of x
        if (((x ^ y) & (x ^ r)) < 0) {
            throw new ArithmeticException("integer overflow");
        }
        return r;
    }

返回x和y的差值,超过long就抛出异常

public static long subtractExact(long x, long y) {
        long r = x - y;
        // HD 2-12 Overflow iff the arguments have different signs and
        // the sign of the result is different than the sign of x
        if (((x ^ y) & (x ^ r)) < 0) {
            throw new ArithmeticException("long overflow");
        }
        return r;
    }

计算x和y的乘积超过int就抛出异常

public static int multiplyExact(int x, int y) {
        long r = (long)x * (long)y;
        if ((int)r != r) {
            throw new ArithmeticException("integer overflow");
        }
        return (int)r;
    }

计算x和y的乘积超过long就抛出异常

public static long multiplyExact(long x, long y) {
        long r = x * y;
        long ax = Math.abs(x);
        long ay = Math.abs(y);
        if (((ax | ay) >>> 31 != 0)) {
           if (((y != 0) && (r / y != x)) ||
               (x == Long.MIN_VALUE && y == -1)) {
                throw new ArithmeticException("long overflow");
            }
        }
        return r;
    }

定义自增1的方法,超过int异常

public static int incrementExact(int a) {
        if (a == Integer.MAX_VALUE) {
            throw new ArithmeticException("integer overflow");
        }

        return a + 1;
    }

定义自增1的方法,超过long异常

public static long incrementExact(long a) {
        if (a == Long.MAX_VALUE) {
            throw new ArithmeticException("long overflow");
        }

        return a + 1L;
    }

定义自减1的方法,超过int就抛出异常

public static int decrementExact(int a) {
        if (a == Integer.MIN_VALUE) {
            throw new ArithmeticException("integer overflow");
        }

        return a - 1;
    }

定义自减1的方法,超过long就抛出异常

public static long decrementExact(long a) {
        if (a == Long.MIN_VALUE) {
            throw new ArithmeticException("long overflow");
        }

        return a - 1L;
    }

定义返回相反数的方法,返回值为int

public static int negateExact(int a) {
        if (a == Integer.MIN_VALUE) {
            throw new ArithmeticException("integer overflow");
        }

        return -a;
    }

定义返回相反数的方法,返回值为long

public static long negateExact(long a) {
        if (a == Long.MIN_VALUE) {
            throw new ArithmeticException("long overflow");
        }

        return -a;
    }

定义将长参数转换为int类型,不相等就报异常

public static int toIntExact(long value) {
        if ((int)value != value) {
            throw new ArithmeticException("integer overflow");
        }
        return (int)value;
    }

定义返回数据整除的部分,返回值为整型

public static int floorDiv(int x, int y) {
        int r = x / y;
        if ((x ^ y) < 0 && (r * y != x)) {
            r--;
        }
        return r;
    }

定义返回数据整除的部分,返回值为长整型

public static long floorDiv(long x, long y) {
        long r = x / y;
        // if the signs are different and modulo not zero, round down
        if ((x ^ y) < 0 && (r * y != x)) {
            r--;
        }
        return r;
    }

返回x除于y的余数,返回值为int类型

public static int floorMod(int x, int y) {
        int r = x - floorDiv(x, y) * y;
        return r;
    }

返回x除于y的余数,返回值为long类型

public static long floorMod(long x, long y) {
        return x - floorDiv(x, y) * y;
    }

返回a的绝对值,传入值为int类型

public static int abs(int a) {
        return (a < 0) ? -a : a;
    }

返回a的绝对值,传入值为long类型

public static long abs(long a) {
        return (a < 0) ? -a : a;
    }

返回a的绝对值,传入值为float类型

public static float abs(float a) {
        return (a <= 0.0F) ? 0.0F - a : a;
    }

返回a的绝对值,传入值为double类型

public static double abs(double a) {
        return (a <= 0.0D) ? 0.0D - a : a;
    }

返回a和b的最大值,返回值为int类型

public static int max(int a, int b) {
        return (a >= b) ? a : b;
    }

返回a和b的最大值,返回值为long类型

public static long max(long a, long b) {
        return (a >= b) ? a : b;
    }

返回a和b的最大值,返回值为float类型

public static float max(float a, float b) {
        if (a != a)
            return a;   // a is NaN
        if ((a == 0.0f) &&
            (b == 0.0f) &&
            (Float.floatToRawIntBits(a) == negativeZeroFloatBits)) {
            // Raw conversion ok since NaN can't map to -0.0.
            return b;
        }
        return (a >= b) ? a : b;
    }

返回a和b的最大值,返回值为double类型

public static double max(double a, double b) {
        if (a != a)
            return a;   // a is NaN
        if ((a == 0.0d) &&
            (b == 0.0d) &&
            (Double.doubleToRawLongBits(a) == negativeZeroDoubleBits)) {
            // Raw conversion ok since NaN can't map to -0.0.
            return b;
        }
        return (a >= b) ? a : b;
    }

返回a和b的最小值,返回值为int类型

public static int min(int a, int b) {
        return (a <= b) ? a : b;
    }

返回a和b的最小值,返回值为long类型

public static long min(long a, long b) {
        return (a <= b) ? a : b;
    }

返回a和b的最小值,返回值为float类型

public static float min(float a, float b) {
        if (a != a)
            return a;   // a is NaN
        if ((a == 0.0f) &&
            (b == 0.0f) &&
            (Float.floatToRawIntBits(b) == negativeZeroFloatBits)) {
            // Raw conversion ok since NaN can't map to -0.0.
            return b;
        }
        return (a <= b) ? a : b;
    }

返回a和b的最小值,返回值为double类型

public static double min(double a, double b) {
        if (a != a)
            return a;   // a is NaN
        if ((a == 0.0d) &&
            (b == 0.0d) &&
            (Double.doubleToRawLongBits(b) == negativeZeroDoubleBits)) {
            // Raw conversion ok since NaN can't map to -0.0.
            return b;
        }
        return (a <= b) ? a : b;
    }

返回精度单位,返回double类型

public static double ulp(double d) {
        int exp = getExponent(d);

        switch(exp) {
        case DoubleConsts.MAX_EXPONENT+1:     
            return Math.abs(d);

        case DoubleConsts.MIN_EXPONENT-1:      
            return Double.MIN_VALUE;

        default:
            assert exp <= DoubleConsts.MAX_EXPONENT && exp >= DoubleConsts.MIN_EXPONENT;

            exp = exp - (DoubleConsts.SIGNIFICAND_WIDTH-1);
            if (exp >= DoubleConsts.MIN_EXPONENT) {
                return powerOfTwoD(exp);
            }
            else {

                return Double.longBitsToDouble(1L <<
                (exp - (DoubleConsts.MIN_EXPONENT - (DoubleConsts.SIGNIFICAND_WIDTH-1)) ));
            }
        }
    }

返回精度单位,返回float类型

public static float ulp(float f) {
        int exp = getExponent(f);

        switch(exp) {
        case FloatConsts.MAX_EXPONENT+1:        // NaN or infinity
            return Math.abs(f);

        case FloatConsts.MIN_EXPONENT-1:        // zero or subnormal
            return FloatConsts.MIN_VALUE;

        default:
            assert exp <= FloatConsts.MAX_EXPONENT && exp >= FloatConsts.MIN_EXPONENT;

            // ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x))
            exp = exp - (FloatConsts.SIGNIFICAND_WIDTH-1);
            if (exp >= FloatConsts.MIN_EXPONENT) {
                return powerOfTwoF(exp);
            }
            else {

                return Float.intBitsToFloat(1 <<
                (exp - (FloatConsts.MIN_EXPONENT - (FloatConsts.SIGNIFICAND_WIDTH-1)) ));
            }
        }
    }

返回符号函数,传入参数为double类型

public static double signum(double d) {
        return (d == 0.0 || Double.isNaN(d))?d:copySign(1.0, d);
    }

返回符号函数,传入参数为float类型

public static float signum(float f) {
        return (f == 0.0f || Float.isNaN(f))?f:copySign(1.0f, f);
    }

返回双曲正弦值

public static double sinh(double x) {
        return StrictMath.sinh(x);
    }

返回反曲正弦值

public static double cosh(double x) {
        return StrictMath.cosh(x);
    }

返回双曲正切值

public static double tanh(double x) {
        return StrictMath.tanh(x);
    }

返回x和y的平方和后再开方

public static double hypot(double x, double y) {
        return StrictMath.hypot(x, y);
    }

返回e的x次方减一

public static double expm1(double x) {
        return StrictMath.expm1(x);
    }

返回log(x+1)

public static double log1p(double x) {
        return StrictMath.log1p(x);
    }

返回带有双精度参数符号的第一个浮点参数。

public static double copySign(double magnitude, double sign) {
        return Double.longBitsToDouble((Double.doubleToRawLongBits(sign) &
                                        (DoubleConsts.SIGN_BIT_MASK)) |
                                       (Double.doubleToRawLongBits(magnitude) &
                                        (DoubleConsts.EXP_BIT_MASK |
                                         DoubleConsts.SIGNIF_BIT_MASK)));
    }

返回带有浮点数参数符号的第一个浮点参数。

public static double copySign(double magnitude, double sign) {
        return Double.longBitsToDouble((Double.doubleToRawLongBits(sign) &
                                        (DoubleConsts.SIGN_BIT_MASK)) |
                                       (Double.doubleToRawLongBits(magnitude) &
                                        (DoubleConsts.EXP_BIT_MASK |
                                         DoubleConsts.SIGNIF_BIT_MASK)));
    }

返回带有第二个浮点参数符号的第一个浮点参数

public static float copySign(float magnitude, float sign) {
        return Float.intBitsToFloat((Float.floatToRawIntBits(sign) &
                                     (FloatConsts.SIGN_BIT_MASK)) |
                                    (Float.floatToRawIntBits(magnitude) &
                                     (FloatConsts.EXP_BIT_MASK |
                                      FloatConsts.SIGNIF_BIT_MASK)));
    }

返回用于表示浮点数的无偏指数。

public static int getExponent(float f) {
        return ((Float.floatToRawIntBits(f) & FloatConsts.EXP_BIT_MASK) >>
                (FloatConsts.SIGNIFICAND_WIDTH - 1)) - FloatConsts.EXP_BIAS;
    }

返回用于表示 double 的无偏指数。

public static int getExponent(double d) {
        return (int)(((Double.doubleToRawLongBits(d) & DoubleConsts.EXP_BIT_MASK) >>
                      (DoubleConsts.SIGNIFICAND_WIDTH - 1)) - DoubleConsts.EXP_BIAS);
    }

返回在第二个参数的方向上与第一个参数相邻的浮点数。如果两个参数比较相等,则返回第二个参数。

public static double nextAfter(double start, double direction) {
        
        if (Double.isNaN(start) || Double.isNaN(direction)) {
            // return a NaN derived from the input NaN(s)
            return start + direction;
        } else if (start == direction) {
            return direction;
        } else {        
            long transducer = Double.doubleToRawLongBits(start + 0.0d);
            if (direction > start) { // Calculate next greater value
                transducer = transducer + (transducer >= 0L ? 1L:-1L);
            } else  { // Calculate next lesser value
                assert direction < start;
                if (transducer > 0L)
                    --transducer;
                else
                    if (transducer < 0L )
                        ++transducer;
                    else
                        transducer = DoubleConsts.SIGN_BIT_MASK | 1L;
            }

            return Double.longBitsToDouble(transducer);
        }
    }

返回在第二个参数的方向上与第一个参数相邻的浮点数。如果两个参数比较相等,则返回与第二个参数等效的值。

public static float nextAfter(float start, double direction) {
      
        if (Float.isNaN(start) || Double.isNaN(direction)) {
            // return a NaN derived from the input NaN(s)
            return start + (float)direction;
        } else if (start == direction) {
            return (float)direction;
        } else {      
            int transducer = Float.floatToRawIntBits(start + 0.0f);
            
            if (direction > start) {// Calculate next greater value
                transducer = transducer + (transducer >= 0 ? 1:-1);
            } else  { // Calculate next lesser value
                assert direction < start;
                if (transducer > 0)
                    --transducer;
                else
                    if (transducer < 0 )
                        ++transducer;
                  
                    else
                        transducer = FloatConsts.SIGN_BIT_MASK | 1;
            }

            return Float.intBitsToFloat(transducer);
        }
    }

返回在正无穷大方向上与 d 相邻的浮点值。这个方法在语义上等同于 nextAfter(d, Double.POSITIVE_INFINITY);但是,nextUp 实现可能比其等效的 nextAfter 调用运行得更快。

public static double nextUp(double d) {
        if( Double.isNaN(d) || d == Double.POSITIVE_INFINITY)
            return d;
        else {
            d += 0.0d;
            return Double.longBitsToDouble(Double.doubleToRawLongBits(d) +
                                           ((d >= 0.0d)?+1L:-1L));
        }
    }

返回正无穷大方向上与 f 相邻的浮点值。这个方法在语义上等价于 nextAfter(f, Float.POSITIVE_INFINITY);但是,nextUp 实现可能比其等效的 nextAfter 调用运行得更快。

public static float nextUp(float f) {
        if( Float.isNaN(f) || f == FloatConsts.POSITIVE_INFINITY)
            return f;
        else {
            f += 0.0f;
            return Float.intBitsToFloat(Float.floatToRawIntBits(f) +
                                        ((f >= 0.0f)?+1:-1));
        }
    }

返回负无穷大方向上与 d 相邻的浮点值。这个方法在语义上等同于 nextAfter(d, Double.NEGATIVE_INFINITY);但是,nextDown 实现可能比其等效的 nextAfter 调用运行得更快。

public static double nextDown(double d) {
        if (Double.isNaN(d) || d == Double.NEGATIVE_INFINITY)
            return d;
        else {
            if (d == 0.0)
                return -Double.MIN_VALUE;
            else
                return Double.longBitsToDouble(Double.doubleToRawLongBits(d) +
                                               ((d > 0.0d)?-1L:+1L));
        }
    }

返回负无穷大方向上与 f 相邻的浮点值。这个方法在语义上等同于 nextAfter(f, Float.NEGATIVE_INFINITY);但是,nextDown 实现可能比其等效的 nextAfter 调用运行得更快。

public static float nextDown(float f) {
        if (Float.isNaN(f) || f == Float.NEGATIVE_INFINITY)
            return f;
        else {
            if (f == 0.0f)
                return -Float.MIN_VALUE;
            else
                return Float.intBitsToFloat(Float.floatToRawIntBits(f) +
                                            ((f > 0.0f)?-1:+1));
        }
    }

返回d 乘上2的scaleFactor次方

public static double scalb(double d, int scaleFactor) {
     
        final int MAX_SCALE = DoubleConsts.MAX_EXPONENT + -DoubleConsts.MIN_EXPONENT +
                              DoubleConsts.SIGNIFICAND_WIDTH + 1;
        int exp_adjust = 0;
        int scale_increment = 0;
        double exp_delta = Double.NaN;

        if(scaleFactor < 0) {
            scaleFactor = Math.max(scaleFactor, -MAX_SCALE);
            scale_increment = -512;
            exp_delta = twoToTheDoubleScaleDown;
        }
        else {
            scaleFactor = Math.min(scaleFactor, MAX_SCALE);
            scale_increment = 512;
            exp_delta = twoToTheDoubleScaleUp;
        }
        int t = (scaleFactor >> 9-1) >>> 32 - 9;
        exp_adjust = ((scaleFactor + t) & (512 -1)) - t;

        d *= powerOfTwoD(exp_adjust);
        scaleFactor -= exp_adjust;

        while(scaleFactor != 0) {
            d *= exp_delta;
            scaleFactor -= scale_increment;
        }
        return d;
    }

定义返回f乘上2的scaleFactor次方

public static float scalb(float f, int scaleFactor) {
      
        final int MAX_SCALE = FloatConsts.MAX_EXPONENT + -FloatConsts.MIN_EXPONENT +
                              FloatConsts.SIGNIFICAND_WIDTH + 1;
        scaleFactor = Math.max(Math.min(scaleFactor, MAX_SCALE), -MAX_SCALE);

        return (float)((double)f*powerOfTwoD(scaleFactor));
    }

返回正常范围内 2 的浮点幂,double类型

static double powerOfTwoD(int n) {
        assert(n >= DoubleConsts.MIN_EXPONENT && n <= DoubleConsts.MAX_EXPONENT);
        return Double.longBitsToDouble((((long)n + (long)DoubleConsts.EXP_BIAS) <<
                                        (DoubleConsts.SIGNIFICAND_WIDTH-1))
                                       & DoubleConsts.EXP_BIT_MASK);
    }

返回正常范围内 2 的浮点幂,float类型

static float powerOfTwoF(int n) {
        assert(n >= FloatConsts.MIN_EXPONENT && n <= FloatConsts.MAX_EXPONENT);
        return Float.intBitsToFloat(((n + FloatConsts.EXP_BIAS) <<
                                     (FloatConsts.SIGNIFICAND_WIDTH-1))
                                    & FloatConsts.EXP_BIT_MASK);
    }
}