int
public static int min(int a, int b) {
return (a <= b) ? a : b;
}
long
public static long min(long a, long b) {
return (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.floatToIntBits(b) == negativeZeroFloatBits)) {
return b;
}
return (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.doubleToLongBits(b) == negativeZeroDoubleBits)) {
return b;
}
return (a <= b) ? a : b;
}
More info: Here
Answer from Gray on Stack OverflowVideos
java - How does math.min actually work? - Stack Overflow
How to use "Math.min" and "Math.max"?
java - How to use Math.min and Math.max in integer array - Stack Overflow
Math.min() and Math.max(): should they still be limited to ...
int
public static int min(int a, int b) {
return (a <= b) ? a : b;
}
long
public static long min(long a, long b) {
return (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.floatToIntBits(b) == negativeZeroFloatBits)) {
return b;
}
return (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.doubleToLongBits(b) == negativeZeroDoubleBits)) {
return b;
}
return (a <= b) ? a : b;
}
More info: Here
Java 7 documentation:
Returns the smaller of two int values. That is, the result the argument closer to the value of Integer.MIN_VALUE. If the arguments have the same value, the result is that same value.
Behaviour:
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
java.lang.Math and java.lang.StrictMath Source:
public static int min(int a, int b) {
return (a <= b) ? a : b;
}
java.lang.Math Bytecode (javap -c Math.class of Oracle's JDK's JRE's 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
If the comparison at 5 is true, a will be loaded, the jvm will jump to 10 and return a, if the comparison yields false, it will jump to 9, which will load and return b.
Intrinsics:
This .hpp file of the Java 8 Hotspot JVM hints that it optimizes Math.min even further with optimized machine code:
do_intrinsic(_min, java_lang_Math, min_name, int2_int_signature, F_S)
This means the above bytecode won't be executed by the Java 8 Hotspot JVM. However, this differs from JVM to JVM, which is why I also explained the bytecode!
Hopefully, now you know all there is to know about Math.min! :)
I'm trying to write a program that takes three int values from the command line and prints them in ascending order, using Math.min() and Math.max(). But I keep getting an error message due to:
int min = Math.min(a, b, c);
int max = Math.max(a, b, c);
int median = a + b + c - min - max;I know that I've written it wrong inside the Maths parentheses, I've tried so many ways including: a "+" b "+" c, a + b +c etc. What am I doing wrong?
These function expect just two arguments. If you want the minimum of an array you can use IntStream.
int[] a = { 1, 5, 6 };
int max = IntStream.of(a).max().orElse(Integer.MIN_VALUE);
int min = IntStream.of(a).min().orElse(Integer.MAX_VALUE);
You can simply used in-build java Collection and Arrays to sort out this problem. You just need to import them and use it.
Please check below code.
import java.util.Arrays;
import java.util.Collections;
public class getMinNMax {
public static void main(String[] args) {
Integer[] num = { 2, 11, 55, 99 };
int min = Collections.min(Arrays.asList(num));
int max = Collections.max(Arrays.asList(num));
System.out.println("Minimum number of array is : " + min);
System.out.println("Maximum number of array is : " + max);
}
}
OP asks for this implementation in a standard library:
int ensureRange(int value, int min, int max) {
return Math.min(Math.max(value, min), max);
}
boolean inRange(int value, int min, int max) {
return (value>= min) && (value<= max);
}
A pity the standard Math library lacks these
I understand this was asked for Java. In Android world, it's common to use Kotlin
and Java combined. In case some Kotlin user reached here (just like me), then they can use coerceIn extension function:
Kotlin Code:
println(10.coerceIn(1, 100)) // 10
println(10.coerceIn(1..100)) // 10
println(0.coerceIn(1, 100)) // 1
println(500.coerceIn(1, 100)) // 100
Read more on official Kotlin Documentation.
Floating-point numbers are way more complicated than integer values.
For this specific case two distinctions are important:
NaNis a valid value forfloatanddoublewhich represents "not a number" and behaves weirdly. Namely, it doesn't compare equal to itself.- Floating point numbers can differentiate between 0.0 and -0.0. A negative zero could conceivably be useful when you're calculating the limit of some function. Distinguishing whether a limit approaches 0 from the positive or the negative direction could be beneficial.
So this part:
if (a != a) {
return a;
}
ensures that NaN is returned if a is NaN (if a is not NaN, but b is, then the "normal" check later on will return b, i.e. NaN, so no explicit check is needed for this case). This is a common pattern: when calculating anything where one input is NaN, the output will also be NaN. Since NaN usually represents some error in the calculation (such as dividing 0 by 0), it's important that it "poisons" all further calculations to ensure the error isn't silently swallowed.
This part:
if (a == 0.0F && b == 0.0F && (long)Float.floatToRawIntBits(b) == negativeZeroFloatBits) {
return b;
}
ensures that if you compare two zero-valued floating point numbers and b is negative zero then that negative zero is returned (since -0.0 is "smaller" than 0.0). Similarly to NaN the normal check will correctly return a if it's -0.0 and b is 0.0.
I recommend carefully reading the documentation for Math.min and also the numeric comparison operators on floating points. Their behaviours are quite different.
Relevant parts from Math.min:
If either value is NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero.
and from JLS ยง15.20.1 "Numerical Comparison Operators <, <=, >, and >="
The result of a floating-point comparison, as determined by the specification of the IEEE 754 standard, is:
If either operand is NaN, then the result is false.
Positive zero and negative zero are considered equal.
If any argument is NaN, Math.min picks that one, but if any operand is NaN, <= evaluates to false. This is why it has to check if a not equal to itself - this would mean a is NaN. If a is not NaN but b is, the last case would cover it.
Math.min also considers -0.0 to be "less than" +0.0, but the numeric comparison operators think they are equal. This is the purpose of the second check.