Class MathUtils
- java.lang.Object
-
- org.apache.commons.math.util.MathUtils
-
public final class MathUtils extends java.lang.Object
Some useful additions to the built-in functions inMath
.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
MathUtils.OrderDirection
Specification of ordering direction.
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static int
addAndCheck(int x, int y)
Add two integers, checking for overflow.static long
addAndCheck(long a, long b)
Add two long integers, checking for overflow.static long
binomialCoefficient(int n, int k)
Returns an exact representation of the Binomial Coefficient, "n choose k
", the number ofk
-element subsets that can be selected from ann
-element set.static double
binomialCoefficientDouble(int n, int k)
Returns adouble
representation of the Binomial Coefficient, "n choose k
", the number ofk
-element subsets that can be selected from ann
-element set.static double
binomialCoefficientLog(int n, int k)
Returns the naturallog
of the Binomial Coefficient, "n choose k
", the number ofk
-element subsets that can be selected from ann
-element set.static void
checkOrder(double[] val)
Checks that the given array is sorted in strictly increasing order.static void
checkOrder(double[] val, int dir, boolean strict)
Deprecated.as of 2.2 (please use the newcheckOrder
method).static void
checkOrder(double[] val, MathUtils.OrderDirection dir, boolean strict)
Checks that the given array is sorted.static int
compareTo(double x, double y, double eps)
Compares two numbers given some amount of allowed error.static double
cosh(double x)
Returns the hyperbolic cosine of x.static double
distance(double[] p1, double[] p2)
Calculates the L2 (Euclidean) distance between two points.static double
distance(int[] p1, int[] p2)
Calculates the L2 (Euclidean) distance between two points.static double
distance1(double[] p1, double[] p2)
Calculates the L1 (sum of abs) distance between two points.static int
distance1(int[] p1, int[] p2)
Calculates the L1 (sum of abs) distance between two points.static double
distanceInf(double[] p1, double[] p2)
Calculates the L∞ (max of abs) distance between two points.static int
distanceInf(int[] p1, int[] p2)
Calculates the L∞ (max of abs) distance between two points.static boolean
equals(double[] x, double[] y)
Returns true iff both arguments are null or have same dimensions and all their elements are equal as defined byequals(double,double)
.static boolean
equals(double x, double y)
Returns true iff both arguments are NaN or neither is NaN and they are equalstatic boolean
equals(double x, double y, double eps)
Returns true if both arguments are equal or within the range of allowed error (inclusive).static boolean
equals(double x, double y, int maxUlps)
Returns true if both arguments are equal or within the range of allowed error (inclusive).static boolean
equals(float[] x, float[] y)
Deprecated.as of 2.2 this method considers thatNaN == NaN
.static boolean
equals(float x, float y)
Deprecated.as of 2.2 his method considers thatNaN == NaN
.static boolean
equals(float x, float y, float eps)
Returns true if both arguments are equal or within the range of allowed error (inclusive).static boolean
equals(float x, float y, int maxUlps)
Returns true if both arguments are equal or within the range of allowed error (inclusive).static boolean
equalsIncludingNaN(double[] x, double[] y)
Returns true iff both arguments are null or have same dimensions and all their elements are equal as defined byequalsIncludingNaN(double,double)
.static boolean
equalsIncludingNaN(double x, double y)
Returns true if both arguments are NaN or neither is NaN and they are equal as defined byequals(x, y, 1)
.static boolean
equalsIncludingNaN(double x, double y, double eps)
Returns true if both arguments are NaN or are equal or within the range of allowed error (inclusive).static boolean
equalsIncludingNaN(double x, double y, int maxUlps)
Returns true if both arguments are NaN or if they are equal as defined byequals(x, y, maxUlps
.static boolean
equalsIncludingNaN(float[] x, float[] y)
Returns true iff both arguments are null or have same dimensions and all their elements are equal as defined byequalsIncludingNaN(float,float)
.static boolean
equalsIncludingNaN(float x, float y)
Returns true if both arguments are NaN or neither is NaN and they are equal as defined byequals(x, y, 1)
.static boolean
equalsIncludingNaN(float x, float y, float eps)
Returns true if both arguments are NaN or are equal or within the range of allowed error (inclusive).static boolean
equalsIncludingNaN(float x, float y, int maxUlps)
Returns true if both arguments are NaN or if they are equal as defined byequals(x, y, maxUlps)
.static long
factorial(int n)
Returns n!.static double
factorialDouble(int n)
Returns n!.static double
factorialLog(int n)
Returns the natural logarithm of n!.static int
gcd(int p, int q)
Gets the greatest common divisor of the absolute value of two numbers, using the "binary gcd" method which avoids division and modulo operations.static long
gcd(long p, long q)
Gets the greatest common divisor of the absolute value of two numbers, using the "binary gcd" method which avoids division and modulo operations.static int
hash(double value)
Returns an integer hash code representing the given double value.static int
hash(double[] value)
Returns an integer hash code representing the given double array.static byte
indicator(byte x)
For a byte value x, this method returns (byte)(+1) if x >= 0 and (byte)(-1) if x < 0.static double
indicator(double x)
For a double precision value x, this method returns +1.0 if x >= 0 and -1.0 if x < 0.static float
indicator(float x)
For a float value x, this method returns +1.0F if x >= 0 and -1.0F if x < 0.static int
indicator(int x)
For an int value x, this method returns +1 if x >= 0 and -1 if x < 0.static long
indicator(long x)
For a long value x, this method returns +1L if x >= 0 and -1L if x < 0.static short
indicator(short x)
For a short value x, this method returns (short)(+1) if x >= 0 and (short)(-1) if x < 0.static int
lcm(int a, int b)
Returns the least common multiple of the absolute value of two numbers, using the formulalcm(a,b) = (a / gcd(a,b)) * b
.static long
lcm(long a, long b)
Returns the least common multiple of the absolute value of two numbers, using the formulalcm(a,b) = (a / gcd(a,b)) * b
.static double
log(double base, double x)
static int
mulAndCheck(int x, int y)
Multiply two integers, checking for overflow.static long
mulAndCheck(long a, long b)
Multiply two long integers, checking for overflow.static double
nextAfter(double d, double direction)
Deprecated.as of 2.2, replaced byFastMath.nextAfter(double, double)
which handles Infinities differently, and returns direction if d and direction compare equal.static double
normalizeAngle(double a, double center)
Normalize an angle in a 2&pi wide interval around a center value.static double[]
normalizeArray(double[] values, double normalizedSum)
Normalizes an array to make it sum to a specified value.static int
pow(int k, int e)
Raise an int to an int power.static int
pow(int k, long e)
Raise an int to a long power.static long
pow(long k, int e)
Raise a long to an int power.static long
pow(long k, long e)
Raise a long to a long power.static java.math.BigInteger
pow(java.math.BigInteger k, int e)
Raise a BigInteger to an int power.static java.math.BigInteger
pow(java.math.BigInteger k, long e)
Raise a BigInteger to a long power.static java.math.BigInteger
pow(java.math.BigInteger k, java.math.BigInteger e)
Raise a BigInteger to a BigInteger power.static double
round(double x, int scale)
Round the given value to the specified number of decimal places.static double
round(double x, int scale, int roundingMethod)
Round the given value to the specified number of decimal places.static float
round(float x, int scale)
Round the given value to the specified number of decimal places.static float
round(float x, int scale, int roundingMethod)
Round the given value to the specified number of decimal places.static double
safeNorm(double[] v)
Returns the Cartesian norm (2-norm), handling both overflow and underflow.static double
scalb(double d, int scaleFactor)
Deprecated.as of 2.2, replaced byFastMath.scalb(double, int)
static byte
sign(byte x)
Returns the sign for byte valuex
.static double
sign(double x)
Returns the sign for double precisionx
.static float
sign(float x)
Returns the sign for float valuex
.static int
sign(int x)
Returns the sign for int valuex
.static long
sign(long x)
Returns the sign for long valuex
.static short
sign(short x)
Returns the sign for short valuex
.static double
sinh(double x)
Returns the hyperbolic sine of x.static int
subAndCheck(int x, int y)
Subtract two integers, checking for overflow.static long
subAndCheck(long a, long b)
Subtract two long integers, checking for overflow.
-
-
-
Field Detail
-
EPSILON
public static final double EPSILON
Smallest positive number such that 1 - EPSILON is not numerically equal to 1.- See Also:
- Constant Field Values
-
SAFE_MIN
public static final double SAFE_MIN
Safe minimum, such that 1 / SAFE_MIN does not overflow.In IEEE 754 arithmetic, this is also the smallest normalized number 2-1022.
- See Also:
- Constant Field Values
-
TWO_PI
public static final double TWO_PI
2 π.- Since:
- 2.1
- See Also:
- Constant Field Values
-
-
Method Detail
-
addAndCheck
public static int addAndCheck(int x, int y)
Add two integers, checking for overflow.- Parameters:
x
- an addendy
- an addend- Returns:
- the sum
x+y
- Throws:
java.lang.ArithmeticException
- if the result can not be represented as an int- Since:
- 1.1
-
addAndCheck
public static long addAndCheck(long a, long b)
Add two long integers, checking for overflow.- Parameters:
a
- an addendb
- an addend- Returns:
- the sum
a+b
- Throws:
java.lang.ArithmeticException
- if the result can not be represented as an long- Since:
- 1.2
-
binomialCoefficient
public static long binomialCoefficient(int n, int k)
Returns an exact representation of the Binomial Coefficient, "n choose k
", the number ofk
-element subsets that can be selected from ann
-element set.Preconditions:
-
0 <= k <= n
(otherwiseIllegalArgumentException
is thrown) - The result is small enough to fit into a
long
. The largest value ofn
for which all coefficients are< Long.MAX_VALUE
is 66. If the computed value exceedsLong.MAX_VALUE
anArithMeticException
is thrown.
- Parameters:
n
- the size of the setk
- the size of the subsets to be counted- Returns:
n choose k
- Throws:
java.lang.IllegalArgumentException
- if preconditions are not met.java.lang.ArithmeticException
- if the result is too large to be represented by a long integer.
-
-
binomialCoefficientDouble
public static double binomialCoefficientDouble(int n, int k)
Returns adouble
representation of the Binomial Coefficient, "n choose k
", the number ofk
-element subsets that can be selected from ann
-element set.Preconditions:
-
0 <= k <= n
(otherwiseIllegalArgumentException
is thrown) - The result is small enough to fit into a
double
. The largest value ofn
for which all coefficients are < Double.MAX_VALUE is 1029. If the computed value exceeds Double.MAX_VALUE, Double.POSITIVE_INFINITY is returned
- Parameters:
n
- the size of the setk
- the size of the subsets to be counted- Returns:
n choose k
- Throws:
java.lang.IllegalArgumentException
- if preconditions are not met.
-
-
binomialCoefficientLog
public static double binomialCoefficientLog(int n, int k)
Returns the naturallog
of the Binomial Coefficient, "n choose k
", the number ofk
-element subsets that can be selected from ann
-element set.Preconditions:
-
0 <= k <= n
(otherwiseIllegalArgumentException
is thrown)
- Parameters:
n
- the size of the setk
- the size of the subsets to be counted- Returns:
n choose k
- Throws:
java.lang.IllegalArgumentException
- if preconditions are not met.
-
-
compareTo
public static int compareTo(double x, double y, double eps)
Compares two numbers given some amount of allowed error.- Parameters:
x
- the first numbery
- the second numbereps
- the amount of error to allow when checking for equality- Returns:
- 0 if
equals(x, y, eps)
- < 0 if !
equals(x, y, eps)
&& x < y - > 0 if !
equals(x, y, eps)
&& x > y
- 0 if
-
cosh
public static double cosh(double x)
Returns the hyperbolic cosine of x.- Parameters:
x
- double value for which to find the hyperbolic cosine- Returns:
- hyperbolic cosine of x
-
equals
@Deprecated public static boolean equals(float x, float y)
Deprecated.as of 2.2 his method considers thatNaN == NaN
. In release 3.0, the semantics will change in order to comply with IEEE754 where it is specified thatNaN != NaN
. New methods have been added for those cases wher the old semantics is useful (see e.g.equalsIncludingNaN
.Returns true iff they are strictly equal.- Parameters:
x
- first valuey
- second value- Returns:
true
if the values are equal.
-
equalsIncludingNaN
public static boolean equalsIncludingNaN(float x, float y)
Returns true if both arguments are NaN or neither is NaN and they are equal as defined byequals(x, y, 1)
.- Parameters:
x
- first valuey
- second value- Returns:
true
if the values are equal or both are NaN.- Since:
- 2.2
-
equals
public static boolean equals(float x, float y, float eps)
Returns true if both arguments are equal or within the range of allowed error (inclusive).- Parameters:
x
- first valuey
- second valueeps
- the amount of absolute error to allow.- Returns:
true
if the values are equal or within range of each other.- Since:
- 2.2
-
equalsIncludingNaN
public static boolean equalsIncludingNaN(float x, float y, float eps)
Returns true if both arguments are NaN or are equal or within the range of allowed error (inclusive).- Parameters:
x
- first valuey
- second valueeps
- the amount of absolute error to allow.- Returns:
true
if the values are equal or within range of each other, or both are NaN.- Since:
- 2.2
-
equals
public static boolean equals(float x, float y, int maxUlps)
Returns true if both arguments are equal or within the range of allowed error (inclusive). Two float numbers are considered equal if there are(maxUlps - 1)
(or fewer) floating point numbers between them, i.e. two adjacent floating point numbers are considered equal. Adapted from Bruce Dawson- Parameters:
x
- first valuey
- second valuemaxUlps
-(maxUlps - 1)
is the number of floating point values betweenx
andy
.- Returns:
true
if there are fewer thanmaxUlps
floating point values betweenx
andy
.- Since:
- 2.2
-
equalsIncludingNaN
public static boolean equalsIncludingNaN(float x, float y, int maxUlps)
Returns true if both arguments are NaN or if they are equal as defined byequals(x, y, maxUlps)
.- Parameters:
x
- first valuey
- second valuemaxUlps
-(maxUlps - 1)
is the number of floating point values betweenx
andy
.- Returns:
true
if both arguments are NaN or if there are less thanmaxUlps
floating point values betweenx
andy
.- Since:
- 2.2
-
equals
@Deprecated public static boolean equals(float[] x, float[] y)
Deprecated.as of 2.2 this method considers thatNaN == NaN
. In release 3.0, the semantics will change in order to comply with IEEE754 where it is specified thatNaN != NaN
. New methods have been added for those cases where the old semantics is useful (see e.g.equalsIncludingNaN
.Returns true iff both arguments are null or have same dimensions and all their elements are equal as defined byequals(float,float)
.- Parameters:
x
- first arrayy
- second array- Returns:
- true if the values are both null or have same dimension and equal elements.
-
equalsIncludingNaN
public static boolean equalsIncludingNaN(float[] x, float[] y)
Returns true iff both arguments are null or have same dimensions and all their elements are equal as defined byequalsIncludingNaN(float,float)
.- Parameters:
x
- first arrayy
- second array- Returns:
- true if the values are both null or have same dimension and equal elements
- Since:
- 2.2
-
equals
public static boolean equals(double x, double y)
Returns true iff both arguments are NaN or neither is NaN and they are equalThis method considers that
NaN == NaN
. In release 3.0, the semantics will change in order to comply with IEEE754 where it is specified thatNaN != NaN
. New methods have been added for those cases where the old semantics (w.r.t. NaN) is useful (see e.g.equalsIncludingNaN
.- Parameters:
x
- first valuey
- second value- Returns:
true
if the values are equal.
-
equalsIncludingNaN
public static boolean equalsIncludingNaN(double x, double y)
Returns true if both arguments are NaN or neither is NaN and they are equal as defined byequals(x, y, 1)
.- Parameters:
x
- first valuey
- second value- Returns:
true
if the values are equal or both are NaN.- Since:
- 2.2
-
equals
public static boolean equals(double x, double y, double eps)
Returns true if both arguments are equal or within the range of allowed error (inclusive).Two NaNs are considered equals, as are two infinities with same sign.
This method considers that
NaN == NaN
. In release 3.0, the semantics will change in order to comply with IEEE754 where it is specified thatNaN != NaN
. New methods have been added for those cases where the old semantics (w.r.t. NaN) is useful (see e.g.equalsIncludingNaN
.- Parameters:
x
- first valuey
- second valueeps
- the amount of absolute error to allow.- Returns:
true
if the values are equal or within range of each other.
-
equalsIncludingNaN
public static boolean equalsIncludingNaN(double x, double y, double eps)
Returns true if both arguments are NaN or are equal or within the range of allowed error (inclusive).- Parameters:
x
- first valuey
- second valueeps
- the amount of absolute error to allow.- Returns:
true
if the values are equal or within range of each other, or both are NaN.- Since:
- 2.2
-
equals
public static boolean equals(double x, double y, int maxUlps)
Returns true if both arguments are equal or within the range of allowed error (inclusive). Two float numbers are considered equal if there are(maxUlps - 1)
(or fewer) floating point numbers between them, i.e. two adjacent floating point numbers are considered equal. Adapted from Bruce DawsonThis method considers that
NaN == NaN
. In release 3.0, the semantics will change in order to comply with IEEE754 where it is specified thatNaN != NaN
. New methods have been added for those cases where the old semantics (w.r.t. NaN) is useful (see e.g.equalsIncludingNaN
.- Parameters:
x
- first valuey
- second valuemaxUlps
-(maxUlps - 1)
is the number of floating point values betweenx
andy
.- Returns:
true
if there are fewer thanmaxUlps
floating point values betweenx
andy
.
-
equalsIncludingNaN
public static boolean equalsIncludingNaN(double x, double y, int maxUlps)
Returns true if both arguments are NaN or if they are equal as defined byequals(x, y, maxUlps
.- Parameters:
x
- first valuey
- second valuemaxUlps
-(maxUlps - 1)
is the number of floating point values betweenx
andy
.- Returns:
true
if both arguments are NaN or if there are less thanmaxUlps
floating point values betweenx
andy
.- Since:
- 2.2
-
equals
public static boolean equals(double[] x, double[] y)
Returns true iff both arguments are null or have same dimensions and all their elements are equal as defined byequals(double,double)
.This method considers that
NaN == NaN
. In release 3.0, the semantics will change in order to comply with IEEE754 where it is specified thatNaN != NaN
. New methods have been added for those cases wher the old semantics is useful (see e.g.equalsIncludingNaN
.- Parameters:
x
- first arrayy
- second array- Returns:
- true if the values are both null or have same dimension and equal elements.
-
equalsIncludingNaN
public static boolean equalsIncludingNaN(double[] x, double[] y)
Returns true iff both arguments are null or have same dimensions and all their elements are equal as defined byequalsIncludingNaN(double,double)
.- Parameters:
x
- first arrayy
- second array- Returns:
- true if the values are both null or have same dimension and equal elements
- Since:
- 2.2
-
factorial
public static long factorial(int n)
Returns n!. Shorthand forn
Factorial, the product of the numbers1,...,n
.Preconditions:
-
n >= 0
(otherwiseIllegalArgumentException
is thrown) - The result is small enough to fit into a
long
. The largest value ofn
for whichn!
< Long.MAX_VALUE is 20. If the computed value exceedsLong.MAX_VALUE
anArithMeticException
is thrown.
- Parameters:
n
- argument- Returns:
n!
- Throws:
java.lang.ArithmeticException
- if the result is too large to be represented by a long integer.java.lang.IllegalArgumentException
- if n < 0
-
-
factorialDouble
public static double factorialDouble(int n)
Returns n!. Shorthand forn
Factorial, the product of the numbers1,...,n
as adouble
.Preconditions:
-
n >= 0
(otherwiseIllegalArgumentException
is thrown) - The result is small enough to fit into a
double
. The largest value ofn
for whichn!
< Double.MAX_VALUE is 170. If the computed value exceeds Double.MAX_VALUE, Double.POSITIVE_INFINITY is returned
- Parameters:
n
- argument- Returns:
n!
- Throws:
java.lang.IllegalArgumentException
- if n < 0
-
-
factorialLog
public static double factorialLog(int n)
Returns the natural logarithm of n!.Preconditions:
-
n >= 0
(otherwiseIllegalArgumentException
is thrown)
- Parameters:
n
- argument- Returns:
n!
- Throws:
java.lang.IllegalArgumentException
- if preconditions are not met.
-
-
gcd
public static int gcd(int p, int q)
Gets the greatest common divisor of the absolute value of two numbers, using the "binary gcd" method which avoids division and modulo operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef Stein (1961).
Special cases:- The invocations
gcd(Integer.MIN_VALUE, Integer.MIN_VALUE)
,gcd(Integer.MIN_VALUE, 0)
andgcd(0, Integer.MIN_VALUE)
throw anArithmeticException
, because the result would be 2^31, which is too large for an int value. - The result of
gcd(x, x)
,gcd(0, x)
andgcd(x, 0)
is the absolute value ofx
, except for the special cases above. - The invocation
gcd(0, 0)
is the only one which returns0
.
- Parameters:
p
- any numberq
- any number- Returns:
- the greatest common divisor, never negative
- Throws:
java.lang.ArithmeticException
- if the result cannot be represented as a nonnegative int value- Since:
- 1.1
- The invocations
-
gcd
public static long gcd(long p, long q)
Gets the greatest common divisor of the absolute value of two numbers, using the "binary gcd" method which avoids division and modulo operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef Stein (1961).
Special cases:- The invocations
gcd(Long.MIN_VALUE, Long.MIN_VALUE)
,gcd(Long.MIN_VALUE, 0L)
andgcd(0L, Long.MIN_VALUE)
throw anArithmeticException
, because the result would be 2^63, which is too large for a long value. - The result of
gcd(x, x)
,gcd(0L, x)
andgcd(x, 0L)
is the absolute value ofx
, except for the special cases above. - The invocation
gcd(0L, 0L)
is the only one which returns0L
.
- Parameters:
p
- any numberq
- any number- Returns:
- the greatest common divisor, never negative
- Throws:
java.lang.ArithmeticException
- if the result cannot be represented as a nonnegative long value- Since:
- 2.1
- The invocations
-
hash
public static int hash(double value)
Returns an integer hash code representing the given double value.- Parameters:
value
- the value to be hashed- Returns:
- the hash code
-
hash
public static int hash(double[] value)
Returns an integer hash code representing the given double array.- Parameters:
value
- the value to be hashed (may be null)- Returns:
- the hash code
- Since:
- 1.2
-
indicator
public static byte indicator(byte x)
For a byte value x, this method returns (byte)(+1) if x >= 0 and (byte)(-1) if x < 0.- Parameters:
x
- the value, a byte- Returns:
- (byte)(+1) or (byte)(-1), depending on the sign of x
-
indicator
public static double indicator(double x)
For a double precision value x, this method returns +1.0 if x >= 0 and -1.0 if x < 0. ReturnsNaN
ifx
isNaN
.- Parameters:
x
- the value, a double- Returns:
- +1.0 or -1.0, depending on the sign of x
-
indicator
public static float indicator(float x)
For a float value x, this method returns +1.0F if x >= 0 and -1.0F if x < 0. ReturnsNaN
ifx
isNaN
.- Parameters:
x
- the value, a float- Returns:
- +1.0F or -1.0F, depending on the sign of x
-
indicator
public static int indicator(int x)
For an int value x, this method returns +1 if x >= 0 and -1 if x < 0.- Parameters:
x
- the value, an int- Returns:
- +1 or -1, depending on the sign of x
-
indicator
public static long indicator(long x)
For a long value x, this method returns +1L if x >= 0 and -1L if x < 0.- Parameters:
x
- the value, a long- Returns:
- +1L or -1L, depending on the sign of x
-
indicator
public static short indicator(short x)
For a short value x, this method returns (short)(+1) if x >= 0 and (short)(-1) if x < 0.- Parameters:
x
- the value, a short- Returns:
- (short)(+1) or (short)(-1), depending on the sign of x
-
lcm
public static int lcm(int a, int b)
Returns the least common multiple of the absolute value of two numbers, using the formula
Special cases:lcm(a,b) = (a / gcd(a,b)) * b
.- The invocations
lcm(Integer.MIN_VALUE, n)
andlcm(n, Integer.MIN_VALUE)
, whereabs(n)
is a power of 2, throw anArithmeticException
, because the result would be 2^31, which is too large for an int value. - The result of
lcm(0, x)
andlcm(x, 0)
is0
for anyx
.
- Parameters:
a
- any numberb
- any number- Returns:
- the least common multiple, never negative
- Throws:
java.lang.ArithmeticException
- if the result cannot be represented as a nonnegative int value- Since:
- 1.1
- The invocations
-
lcm
public static long lcm(long a, long b)
Returns the least common multiple of the absolute value of two numbers, using the formula
Special cases:lcm(a,b) = (a / gcd(a,b)) * b
.- The invocations
lcm(Long.MIN_VALUE, n)
andlcm(n, Long.MIN_VALUE)
, whereabs(n)
is a power of 2, throw anArithmeticException
, because the result would be 2^63, which is too large for an int value. - The result of
lcm(0L, x)
andlcm(x, 0L)
is0L
for anyx
.
- Parameters:
a
- any numberb
- any number- Returns:
- the least common multiple, never negative
- Throws:
java.lang.ArithmeticException
- if the result cannot be represented as a nonnegative long value- Since:
- 2.1
- The invocations
-
log
public static double log(double base, double x)
Returns the logarithm for base
b
ofx
.Returns
NaN
if either argument is negative. If
base
is 0 andx
is positive, 0 is returned. Ifbase
is positive andx
is 0,Double.NEGATIVE_INFINITY
is returned. If both arguments are 0, the result isNaN
.- Parameters:
base
- the base of the logarithm, must be greater than 0x
- argument, must be greater than 0- Returns:
- the value of the logarithm - the number y such that base^y = x.
- Since:
- 1.2
-
mulAndCheck
public static int mulAndCheck(int x, int y)
Multiply two integers, checking for overflow.- Parameters:
x
- a factory
- a factor- Returns:
- the product
x*y
- Throws:
java.lang.ArithmeticException
- if the result can not be represented as an int- Since:
- 1.1
-
mulAndCheck
public static long mulAndCheck(long a, long b)
Multiply two long integers, checking for overflow.- Parameters:
a
- first valueb
- second value- Returns:
- the product
a * b
- Throws:
java.lang.ArithmeticException
- if the result can not be represented as an long- Since:
- 1.2
-
nextAfter
@Deprecated public static double nextAfter(double d, double direction)
Deprecated.as of 2.2, replaced byFastMath.nextAfter(double, double)
which handles Infinities differently, and returns direction if d and direction compare equal.Get the next machine representable number after a number, moving in the direction of another number.If
direction
is greater than or equal tod
, the smallest machine representable number strictly greater thand
is returned; otherwise the largest representable number strictly less thand
is returned.If
d
is NaN or Infinite, it is returned unchanged.- Parameters:
d
- base numberdirection
- (the only important thing is whether direction is greater or smaller than d)- Returns:
- the next machine representable number in the specified direction
- Since:
- 1.2
-
scalb
@Deprecated public static double scalb(double d, int scaleFactor)
Deprecated.as of 2.2, replaced byFastMath.scalb(double, int)
Scale a number by 2scaleFactor.If
d
is 0 or NaN or Infinite, it is returned unchanged.- Parameters:
d
- base numberscaleFactor
- power of two by which d should be multiplied- Returns:
- d × 2scaleFactor
- Since:
- 2.0
-
normalizeAngle
public static double normalizeAngle(double a, double center)
Normalize an angle in a 2&pi wide interval around a center value.This method has three main uses:
- normalize an angle between 0 and 2π:
a = MathUtils.normalizeAngle(a, FastMath.PI);
- normalize an angle between -π and +π
a = MathUtils.normalizeAngle(a, 0.0);
- compute the angle between two defining angular positions:
angle = MathUtils.normalizeAngle(end, start) - start;
Note that due to numerical accuracy and since π cannot be represented exactly, the result interval is closed, it cannot be half-closed as would be more satisfactory in a purely mathematical view.
- Parameters:
a
- angle to normalizecenter
- center of the desired 2π interval for the result- Returns:
- a-2kπ with integer k and center-π <= a-2kπ <= center+π
- Since:
- 1.2
- normalize an angle between 0 and 2π:
-
normalizeArray
public static double[] normalizeArray(double[] values, double normalizedSum) throws java.lang.ArithmeticException, java.lang.IllegalArgumentException
Normalizes an array to make it sum to a specified value. Returns the result of the transformation
x |-> x * normalizedSum / sum
applied to each non-NaN element x of the input array, where sum is the sum of the non-NaN entries in the input array.Throws IllegalArgumentException if
normalizedSum
is infinite or NaN and ArithmeticException if the input array contains any infinite elements or sums to 0Ignores (i.e., copies unchanged to the output array) NaNs in the input array.
- Parameters:
values
- input array to be normalizednormalizedSum
- target sum for the normalized array- Returns:
- normalized array
- Throws:
java.lang.ArithmeticException
- if the input array contains infinite elements or sums to zerojava.lang.IllegalArgumentException
- if the target sum is infinite or NaN- Since:
- 2.1
-
round
public static double round(double x, int scale)
Round the given value to the specified number of decimal places. The value is rounded using theBigDecimal.ROUND_HALF_UP
method.- Parameters:
x
- the value to round.scale
- the number of digits to the right of the decimal point.- Returns:
- the rounded value.
- Since:
- 1.1
-
round
public static double round(double x, int scale, int roundingMethod)
Round the given value to the specified number of decimal places. The value is rounded using the given method which is any method defined inBigDecimal
.- Parameters:
x
- the value to round.scale
- the number of digits to the right of the decimal point.roundingMethod
- the rounding method as defined inBigDecimal
.- Returns:
- the rounded value.
- Since:
- 1.1
-
round
public static float round(float x, int scale)
Round the given value to the specified number of decimal places. The value is rounding using theBigDecimal.ROUND_HALF_UP
method.- Parameters:
x
- the value to round.scale
- the number of digits to the right of the decimal point.- Returns:
- the rounded value.
- Since:
- 1.1
-
round
public static float round(float x, int scale, int roundingMethod)
Round the given value to the specified number of decimal places. The value is rounded using the given method which is any method defined inBigDecimal
.- Parameters:
x
- the value to round.scale
- the number of digits to the right of the decimal point.roundingMethod
- the rounding method as defined inBigDecimal
.- Returns:
- the rounded value.
- Since:
- 1.1
-
sign
public static byte sign(byte x)
Returns the sign for byte valuex
.For a byte value x, this method returns (byte)(+1) if x > 0, (byte)(0) if x = 0, and (byte)(-1) if x < 0.
- Parameters:
x
- the value, a byte- Returns:
- (byte)(+1), (byte)(0), or (byte)(-1), depending on the sign of x
-
sign
public static double sign(double x)
Returns the sign for double precisionx
.For a double value
x
, this method returns+1.0
ifx > 0
,0.0
ifx = 0.0
, and-1.0
ifx < 0
. ReturnsNaN
ifx
isNaN
.- Parameters:
x
- the value, a double- Returns:
- +1.0, 0.0, or -1.0, depending on the sign of x
-
sign
public static float sign(float x)
Returns the sign for float valuex
.For a float value x, this method returns +1.0F if x > 0, 0.0F if x = 0.0F, and -1.0F if x < 0. Returns
NaN
ifx
isNaN
.- Parameters:
x
- the value, a float- Returns:
- +1.0F, 0.0F, or -1.0F, depending on the sign of x
-
sign
public static int sign(int x)
Returns the sign for int valuex
.For an int value x, this method returns +1 if x > 0, 0 if x = 0, and -1 if x < 0.
- Parameters:
x
- the value, an int- Returns:
- +1, 0, or -1, depending on the sign of x
-
sign
public static long sign(long x)
Returns the sign for long valuex
.For a long value x, this method returns +1L if x > 0, 0L if x = 0, and -1L if x < 0.
- Parameters:
x
- the value, a long- Returns:
- +1L, 0L, or -1L, depending on the sign of x
-
sign
public static short sign(short x)
Returns the sign for short valuex
.For a short value x, this method returns (short)(+1) if x > 0, (short)(0) if x = 0, and (short)(-1) if x < 0.
- Parameters:
x
- the value, a short- Returns:
- (short)(+1), (short)(0), or (short)(-1), depending on the sign of x
-
sinh
public static double sinh(double x)
Returns the hyperbolic sine of x.- Parameters:
x
- double value for which to find the hyperbolic sine- Returns:
- hyperbolic sine of x
-
subAndCheck
public static int subAndCheck(int x, int y)
Subtract two integers, checking for overflow.- Parameters:
x
- the minuendy
- the subtrahend- Returns:
- the difference
x-y
- Throws:
java.lang.ArithmeticException
- if the result can not be represented as an int- Since:
- 1.1
-
subAndCheck
public static long subAndCheck(long a, long b)
Subtract two long integers, checking for overflow.- Parameters:
a
- first valueb
- second value- Returns:
- the difference
a-b
- Throws:
java.lang.ArithmeticException
- if the result can not be represented as an long- Since:
- 1.2
-
pow
public static int pow(int k, int e) throws java.lang.IllegalArgumentException
Raise an int to an int power.- Parameters:
k
- number to raisee
- exponent (must be positive or null)- Returns:
- ke
- Throws:
java.lang.IllegalArgumentException
- if e is negative
-
pow
public static int pow(int k, long e) throws java.lang.IllegalArgumentException
Raise an int to a long power.- Parameters:
k
- number to raisee
- exponent (must be positive or null)- Returns:
- ke
- Throws:
java.lang.IllegalArgumentException
- if e is negative
-
pow
public static long pow(long k, int e) throws java.lang.IllegalArgumentException
Raise a long to an int power.- Parameters:
k
- number to raisee
- exponent (must be positive or null)- Returns:
- ke
- Throws:
java.lang.IllegalArgumentException
- if e is negative
-
pow
public static long pow(long k, long e) throws java.lang.IllegalArgumentException
Raise a long to a long power.- Parameters:
k
- number to raisee
- exponent (must be positive or null)- Returns:
- ke
- Throws:
java.lang.IllegalArgumentException
- if e is negative
-
pow
public static java.math.BigInteger pow(java.math.BigInteger k, int e) throws java.lang.IllegalArgumentException
Raise a BigInteger to an int power.- Parameters:
k
- number to raisee
- exponent (must be positive or null)- Returns:
- ke
- Throws:
java.lang.IllegalArgumentException
- if e is negative
-
pow
public static java.math.BigInteger pow(java.math.BigInteger k, long e) throws java.lang.IllegalArgumentException
Raise a BigInteger to a long power.- Parameters:
k
- number to raisee
- exponent (must be positive or null)- Returns:
- ke
- Throws:
java.lang.IllegalArgumentException
- if e is negative
-
pow
public static java.math.BigInteger pow(java.math.BigInteger k, java.math.BigInteger e) throws java.lang.IllegalArgumentException
Raise a BigInteger to a BigInteger power.- Parameters:
k
- number to raisee
- exponent (must be positive or null)- Returns:
- ke
- Throws:
java.lang.IllegalArgumentException
- if e is negative
-
distance1
public static double distance1(double[] p1, double[] p2)
Calculates the L1 (sum of abs) distance between two points.- Parameters:
p1
- the first pointp2
- the second point- Returns:
- the L1 distance between the two points
-
distance1
public static int distance1(int[] p1, int[] p2)
Calculates the L1 (sum of abs) distance between two points.- Parameters:
p1
- the first pointp2
- the second point- Returns:
- the L1 distance between the two points
-
distance
public static double distance(double[] p1, double[] p2)
Calculates the L2 (Euclidean) distance between two points.- Parameters:
p1
- the first pointp2
- the second point- Returns:
- the L2 distance between the two points
-
distance
public static double distance(int[] p1, int[] p2)
Calculates the L2 (Euclidean) distance between two points.- Parameters:
p1
- the first pointp2
- the second point- Returns:
- the L2 distance between the two points
-
distanceInf
public static double distanceInf(double[] p1, double[] p2)
Calculates the L∞ (max of abs) distance between two points.- Parameters:
p1
- the first pointp2
- the second point- Returns:
- the L∞ distance between the two points
-
distanceInf
public static int distanceInf(int[] p1, int[] p2)
Calculates the L∞ (max of abs) distance between two points.- Parameters:
p1
- the first pointp2
- the second point- Returns:
- the L∞ distance between the two points
-
checkOrder
public static void checkOrder(double[] val, MathUtils.OrderDirection dir, boolean strict)
Checks that the given array is sorted.- Parameters:
val
- Values.dir
- Ordering direction.strict
- Whether the order should be strict.- Throws:
NonMonotonousSequenceException
- if the array is not sorted.- Since:
- 2.2
-
checkOrder
public static void checkOrder(double[] val)
Checks that the given array is sorted in strictly increasing order.- Parameters:
val
- Values.- Throws:
NonMonotonousSequenceException
- if the array is not sorted.- Since:
- 2.2
-
checkOrder
@Deprecated public static void checkOrder(double[] val, int dir, boolean strict)
Deprecated.as of 2.2 (please use the newcheckOrder
method). To be removed in 3.0.Checks that the given array is sorted.- Parameters:
val
- Valuesdir
- Order direction (-1 for decreasing, 1 for increasing)strict
- Whether the order should be strict- Throws:
NonMonotonousSequenceException
- if the array is not sorted.
-
safeNorm
public static double safeNorm(double[] v)
Returns the Cartesian norm (2-norm), handling both overflow and underflow. Translation of the minpack enorm subroutine. The redistribution policy for MINPACK is available here, for convenience, it is reproduced below.Minpack Copyright Notice (1999) University of Chicago. All rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
- The end-user documentation included with the redistribution, if any,
must include the following acknowledgment:
This product includes software developed by the University of Chicago, as Operator of Argonne National Laboratory.
Alternately, this acknowledgment may appear in the software itself, if and wherever such third-party acknowledgments normally appear. - WARRANTY DISCLAIMER. THE SOFTWARE IS SUPPLIED "AS IS" WITHOUT WARRANTY OF ANY KIND. THE COPYRIGHT HOLDER, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF ENERGY, AND THEIR EMPLOYEES: (1) DISCLAIM ANY WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR NON-INFRINGEMENT, (2) DO NOT ASSUME ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, OR USEFULNESS OF THE SOFTWARE, (3) DO NOT REPRESENT THAT USE OF THE SOFTWARE WOULD NOT INFRINGE PRIVATELY OWNED RIGHTS, (4) DO NOT WARRANT THAT THE SOFTWARE WILL FUNCTION UNINTERRUPTED, THAT IT IS ERROR-FREE OR THAT ANY ERRORS WILL BE CORRECTED.
- LIMITATION OF LIABILITY. IN NO EVENT WILL THE COPYRIGHT HOLDER, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF ENERGY, OR THEIR EMPLOYEES: BE LIABLE FOR ANY INDIRECT, INCIDENTAL, CONSEQUENTIAL, SPECIAL OR PUNITIVE DAMAGES OF ANY KIND OR NATURE, INCLUDING BUT NOT LIMITED TO LOSS OF PROFITS OR LOSS OF DATA, FOR ANY REASON WHATSOEVER, WHETHER SUCH LIABILITY IS ASSERTED ON THE BASIS OF CONTRACT, TORT (INCLUDING NEGLIGENCE OR STRICT LIABILITY), OR OTHERWISE, EVEN IF ANY OF SAID PARTIES HAS BEEN WARNED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGES.
- Parameters:
v
- vector of doubles- Returns:
- the 2-norm of the vector
- Since:
- 2.2
-
-