math.min实际上如何工作?

Sam*_*son 10 java math min built-in

据我所知,java中的所有数学函数都是内置的.但我好奇地想知道它是如何Math.min()工作的?

我检查了java文档,找不到任何可以帮助我的东西.我对java很新.

Gra*_*ray 18

INT

public static int min(int a, int b) {
    return (a <= b) ? a : b;
}
Run Code Online (Sandbox Code Playgroud)

public static long min(long a, long b) {
     return (a <= b) ? a : b;
}
Run Code Online (Sandbox Code Playgroud)

浮动

public static float min(float a, float b) {
    if (a != a) return a;   // a is NaN
    if ((a == 0.0f) && (b == 0.0f) && (Float.floatToIntBits(b) == negativeZeroFloatBits)) {
         return b;
    }
    return (a <= b) ? a : b;
 }
Run Code Online (Sandbox Code Playgroud)

public static double min(double a, double b) {
    if (a != a) return a;   // a is NaN
    if ((a == 0.0d) && (b == 0.0d) && (Double.doubleToLongBits(b) == negativeZeroDoubleBits)) {
        return b;
    }
    return (a <= b) ? a : b;
}
Run Code Online (Sandbox Code Playgroud)

更多信息:这里


til*_*ner 10

Java 7文档:

返回两个int值中较小的一个.也就是说,结果参数更接近Integer.MIN_VALUE的值.如果参数具有相同的值,则结果是相同的值.

行为:

Math.min(1, 2) => 1
Math.min(1F, 2) => 1F
Math.min(3D, 2F) => 2D
Math.min(-0F, 0F) => -0F
Math.min(0D, -0D) => -0D
Math.min(Float.NaN, -2) => Float.NaN
Math.min(-2F, Double.NaN) => Double.NaN
Run Code Online (Sandbox Code Playgroud)

java.lang.Math和java.lang.StrictMath来源:

public static int min(int a, int b) {
    return (a <= b) ? a : b;
}
Run Code Online (Sandbox Code Playgroud)

java.lang.Math Bytecode(javap -c Math.classOracle的JDK的JRE的rt.jar):

public static int min(int, int);
Code:
   0: iload_0           // loads a onto the stack
   1: iload_1           // loads b onto the stack
   2: if_icmpgt     9   // pops two ints (a, b) from the stack
                        // and compares them
                        // if b>a, the jvm continues at label 9
                        // else, at the next instruction, 5
                        // icmpgt is for integer-compare-greater-than
   5: iload_0           // loads a onto the stack
   6: goto          10  // jumps to label 10
   9: iload_1           // loads 
  10: ireturn           // returns the currently loaded integer
Run Code Online (Sandbox Code Playgroud)

如果在比较5是真实的,一个将被装载时,JVM将跳到10,并返回一个,如果该比较产生假的,它将跳到9,这将载入并返回b.

内在性:

Java 8 Hotspot JVM的这个.hpp文件暗示它使用优化的机器代码进一步优化Math.min:

do_intrinsic(_min, java_lang_Math, min_name, int2_int_signature, F_S)
Run Code Online (Sandbox Code Playgroud)

这意味着Java 8 Hotspot JVM将不会执行上述字节码.但是,这与JVM到JVM不同,这也是我解释字节码的原因!

希望你现在知道所有关于Math.min的知识!:)