Class MathUtils

java.lang.Object
org.apache.commons.math.util.MathUtils

public final class MathUtils extends Object
Some useful additions to the built-in functions in Math.
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    static enum 
    Specification of ordering direction.
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final double
    Smallest positive number such that 1 - EPSILON is not numerically equal to 1.
    static final double
    Safe minimum, such that 1 / SAFE_MIN does not overflow.
    static final double
    2 π.
  • Method Summary

    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 of k-element subsets that can be selected from an n-element set.
    static double
    Returns a double representation of the Binomial Coefficient, "n choose k", the number of k-element subsets that can be selected from an n-element set.
    static double
    binomialCoefficientLog(int n, int k)
    Returns the natural log of the Binomial Coefficient, "n choose k", the number of k-element subsets that can be selected from an n-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 new checkOrder 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 by equals(double,double).
    static boolean
    equals(double x, double y)
    Returns true iff both arguments are NaN or neither is NaN and they are equal
    static 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 that NaN == NaN.
    static boolean
    equals(float x, float y)
    Deprecated.
    as of 2.2 his method considers that NaN == 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 by equalsIncludingNaN(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 by equals(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 by equals(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 by equalsIncludingNaN(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 by equals(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 by equals(x, y, maxUlps).
    static long
    factorial(int n)
    Returns n!.
    static double
    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 invalid input: '<' 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 invalid input: '<' 0.
    static float
    indicator(float x)
    For a float value x, this method returns +1.0F if x >= 0 and -1.0F if x invalid input: '<' 0.
    static int
    indicator(int x)
    For an int value x, this method returns +1 if x >= 0 and -1 if x invalid input: '<' 0.
    static long
    indicator(long x)
    For a long value x, this method returns +1L if x >= 0 and -1L if x invalid input: '<' 0.
    static short
    indicator(short x)
    For a short value x, this method returns (short)(+1) if x >= 0 and (short)(-1) if x invalid input: '<' 0.
    static int
    lcm(int a, int b)
    Returns the least common multiple of the absolute value of two numbers, using the formula lcm(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 formula lcm(a,b) = (a / gcd(a,b)) * b.
    static double
    log(double base, double x)
    Returns the logarithm for base b of 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 by FastMath.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 2invalid input: '&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 BigInteger
    pow(BigInteger k, int e)
    Raise a BigInteger to an int power.
    static BigInteger
    pow(BigInteger k, long e)
    Raise a BigInteger to a long power.
    static BigInteger
    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 by FastMath.scalb(double, int)
    static byte
    sign(byte x)
    Returns the sign for byte value x.
    static double
    sign(double x)
    Returns the sign for double precision x.
    static float
    sign(float x)
    Returns the sign for float value x.
    static int
    sign(int x)
    Returns the sign for int value x.
    static long
    sign(long x)
    Returns the sign for long value x.
    static short
    sign(short x)
    Returns the sign for short value x.
    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.

    Methods inherited from class java.lang.Object

    equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • EPSILON

      public static final double EPSILON
      Smallest positive number such that 1 - EPSILON is not numerically equal to 1.
      See Also:
    • 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:
    • TWO_PI

      public static final double TWO_PI
      2 π.
      Since:
      2.1
      See Also:
  • Method Details

    • addAndCheck

      public static int addAndCheck(int x, int y)
      Add two integers, checking for overflow.
      Parameters:
      x - an addend
      y - an addend
      Returns:
      the sum x+y
      Throws:
      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 addend
      b - an addend
      Returns:
      the sum a+b
      Throws:
      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 of k-element subsets that can be selected from an n-element set.

      Preconditions:

      • 0 invalid input: '<'= k invalid input: '<'= n (otherwise IllegalArgumentException is thrown)
      • The result is small enough to fit into a long. The largest value of n for which all coefficients are invalid input: '<' Long.MAX_VALUE is 66. If the computed value exceeds Long.MAX_VALUE an ArithMeticException is thrown.

      Parameters:
      n - the size of the set
      k - the size of the subsets to be counted
      Returns:
      n choose k
      Throws:
      IllegalArgumentException - if preconditions are not met.
      ArithmeticException - if the result is too large to be represented by a long integer.
    • binomialCoefficientDouble

      public static double binomialCoefficientDouble(int n, int k)
      Returns a double representation of the Binomial Coefficient, "n choose k", the number of k-element subsets that can be selected from an n-element set.

      Preconditions:

      • 0 invalid input: '<'= k invalid input: '<'= n (otherwise IllegalArgumentException is thrown)
      • The result is small enough to fit into a double. The largest value of n for which all coefficients are invalid input: '<' Double.MAX_VALUE is 1029. If the computed value exceeds Double.MAX_VALUE, Double.POSITIVE_INFINITY is returned

      Parameters:
      n - the size of the set
      k - the size of the subsets to be counted
      Returns:
      n choose k
      Throws:
      IllegalArgumentException - if preconditions are not met.
    • binomialCoefficientLog

      public static double binomialCoefficientLog(int n, int k)
      Returns the natural log of the Binomial Coefficient, "n choose k", the number of k-element subsets that can be selected from an n-element set.

      Preconditions:

      • 0 invalid input: '<'= k invalid input: '<'= n (otherwise IllegalArgumentException is thrown)

      Parameters:
      n - the size of the set
      k - the size of the subsets to be counted
      Returns:
      n choose k
      Throws:
      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 number
      y - the second number
      eps - the amount of error to allow when checking for equality
      Returns:
    • 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 that NaN == NaN. In release 3.0, the semantics will change in order to comply with IEEE754 where it is specified that NaN != 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 value
      y - 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 by equals(x, y, 1).
      Parameters:
      x - first value
      y - 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 value
      y - second value
      eps - 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 value
      y - second value
      eps - 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 value
      y - second value
      maxUlps - (maxUlps - 1) is the number of floating point values between x and y.
      Returns:
      true if there are fewer than maxUlps floating point values between x and y.
      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 by equals(x, y, maxUlps).
      Parameters:
      x - first value
      y - second value
      maxUlps - (maxUlps - 1) is the number of floating point values between x and y.
      Returns:
      true if both arguments are NaN or if there are less than maxUlps floating point values between x and y.
      Since:
      2.2
    • equals

      @Deprecated public static boolean equals(float[] x, float[] y)
      Deprecated.
      as of 2.2 this method considers that NaN == NaN. In release 3.0, the semantics will change in order to comply with IEEE754 where it is specified that NaN != 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 by equals(float,float).
      Parameters:
      x - first array
      y - 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 by equalsIncludingNaN(float,float).
      Parameters:
      x - first array
      y - 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 equal

      This method considers that NaN == NaN. In release 3.0, the semantics will change in order to comply with IEEE754 where it is specified that NaN != 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 value
      y - 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 by equals(x, y, 1).
      Parameters:
      x - first value
      y - 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 that NaN != 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 value
      y - second value
      eps - 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 value
      y - second value
      eps - 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 Dawson

      This method considers that NaN == NaN. In release 3.0, the semantics will change in order to comply with IEEE754 where it is specified that NaN != 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 value
      y - second value
      maxUlps - (maxUlps - 1) is the number of floating point values between x and y.
      Returns:
      true if there are fewer than maxUlps floating point values between x and y.
    • 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 by equals(x, y, maxUlps.
      Parameters:
      x - first value
      y - second value
      maxUlps - (maxUlps - 1) is the number of floating point values between x and y.
      Returns:
      true if both arguments are NaN or if there are less than maxUlps floating point values between x and y.
      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 by equals(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 that NaN != NaN. New methods have been added for those cases wher the old semantics is useful (see e.g. equalsIncludingNaN.

      Parameters:
      x - first array
      y - 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 by equalsIncludingNaN(double,double).
      Parameters:
      x - first array
      y - 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 for n Factorial, the product of the numbers 1,...,n.

      Preconditions:

      • n >= 0 (otherwise IllegalArgumentException is thrown)
      • The result is small enough to fit into a long. The largest value of n for which n! invalid input: '<' Long.MAX_VALUE is 20. If the computed value exceeds Long.MAX_VALUE an ArithMeticException is thrown.

      Parameters:
      n - argument
      Returns:
      n!
      Throws:
      ArithmeticException - if the result is too large to be represented by a long integer.
      IllegalArgumentException - if n invalid input: '<' 0
    • factorialDouble

      public static double factorialDouble(int n)
      Returns n!. Shorthand for n Factorial, the product of the numbers 1,...,n as a double.

      Preconditions:

      • n >= 0 (otherwise IllegalArgumentException is thrown)
      • The result is small enough to fit into a double. The largest value of n for which n! invalid input: '<' Double.MAX_VALUE is 170. If the computed value exceeds Double.MAX_VALUE, Double.POSITIVE_INFINITY is returned

      Parameters:
      n - argument
      Returns:
      n!
      Throws:
      IllegalArgumentException - if n invalid input: '<' 0
    • factorialLog

      public static double factorialLog(int n)
      Returns the natural logarithm of n!.

      Preconditions:

      • n >= 0 (otherwise IllegalArgumentException is thrown)

      Parameters:
      n - argument
      Returns:
      n!
      Throws:
      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) and gcd(0, Integer.MIN_VALUE) throw an ArithmeticException, because the result would be 2^31, which is too large for an int value.
      • The result of gcd(x, x), gcd(0, x) and gcd(x, 0) is the absolute value of x, except for the special cases above.
      • The invocation gcd(0, 0) is the only one which returns 0.
      Parameters:
      p - any number
      q - any number
      Returns:
      the greatest common divisor, never negative
      Throws:
      ArithmeticException - if the result cannot be represented as a nonnegative int value
      Since:
      1.1
    • 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) and gcd(0L, Long.MIN_VALUE) throw an ArithmeticException, because the result would be 2^63, which is too large for a long value.
      • The result of gcd(x, x), gcd(0L, x) and gcd(x, 0L) is the absolute value of x, except for the special cases above.
      • The invocation gcd(0L, 0L) is the only one which returns 0L.
      Parameters:
      p - any number
      q - any number
      Returns:
      the greatest common divisor, never negative
      Throws:
      ArithmeticException - if the result cannot be represented as a nonnegative long value
      Since:
      2.1
    • 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 invalid input: '<' 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 invalid input: '<' 0. Returns NaN if x is NaN.
      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 invalid input: '<' 0. Returns NaN if x is NaN.
      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 invalid input: '<' 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 invalid input: '<' 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 invalid input: '<' 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 lcm(a,b) = (a / gcd(a,b)) * b.

      Special cases:
      • The invocations lcm(Integer.MIN_VALUE, n) and lcm(n, Integer.MIN_VALUE), where abs(n) is a power of 2, throw an ArithmeticException, because the result would be 2^31, which is too large for an int value.
      • The result of lcm(0, x) and lcm(x, 0) is 0 for any x.
      Parameters:
      a - any number
      b - any number
      Returns:
      the least common multiple, never negative
      Throws:
      ArithmeticException - if the result cannot be represented as a nonnegative int value
      Since:
      1.1
    • lcm

      public static long lcm(long a, long b)

      Returns the least common multiple of the absolute value of two numbers, using the formula lcm(a,b) = (a / gcd(a,b)) * b.

      Special cases:
      • The invocations lcm(Long.MIN_VALUE, n) and lcm(n, Long.MIN_VALUE), where abs(n) is a power of 2, throw an ArithmeticException, because the result would be 2^63, which is too large for an int value.
      • The result of lcm(0L, x) and lcm(x, 0L) is 0L for any x.
      Parameters:
      a - any number
      b - any number
      Returns:
      the least common multiple, never negative
      Throws:
      ArithmeticException - if the result cannot be represented as a nonnegative long value
      Since:
      2.1
    • log

      public static double log(double base, double x)

      Returns the logarithm for base b of x.

      Returns NaN if either argument is negative. If base is 0 and x is positive, 0 is returned. If base is positive and x is 0, Double.NEGATIVE_INFINITY is returned. If both arguments are 0, the result is NaN.

      Parameters:
      base - the base of the logarithm, must be greater than 0
      x - 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 factor
      y - a factor
      Returns:
      the product x*y
      Throws:
      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 value
      b - second value
      Returns:
      the product a * b
      Throws:
      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 by FastMath.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 than d is returned; otherwise the largest representable number strictly less than d is returned.

      If d is NaN or Infinite, it is returned unchanged.

      Parameters:
      d - base number
      direction - (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 by FastMath.scalb(double, int)
      Scale a number by 2scaleFactor.

      If d is 0 or NaN or Infinite, it is returned unchanged.

      Parameters:
      d - base number
      scaleFactor - 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 2invalid input: '&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 normalize
      center - center of the desired 2π interval for the result
      Returns:
      a-2kπ with integer k and center-π <= a-2kπ <= center+π
      Since:
      1.2
    • normalizeArray

      public static double[] normalizeArray(double[] values, double normalizedSum) throws ArithmeticException, 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 0

      Ignores (i.e., copies unchanged to the output array) NaNs in the input array.

      Parameters:
      values - input array to be normalized
      normalizedSum - target sum for the normalized array
      Returns:
      normalized array
      Throws:
      ArithmeticException - if the input array contains infinite elements or sums to zero
      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 the BigDecimal.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 in BigDecimal.
      Parameters:
      x - the value to round.
      scale - the number of digits to the right of the decimal point.
      roundingMethod - the rounding method as defined in BigDecimal.
      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 the BigDecimal.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 in BigDecimal.
      Parameters:
      x - the value to round.
      scale - the number of digits to the right of the decimal point.
      roundingMethod - the rounding method as defined in BigDecimal.
      Returns:
      the rounded value.
      Since:
      1.1
    • sign

      public static byte sign(byte x)
      Returns the sign for byte value x.

      For a byte value x, this method returns (byte)(+1) if x > 0, (byte)(0) if x = 0, and (byte)(-1) if x invalid input: '<' 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 precision x.

      For a double value x, this method returns +1.0 if x > 0, 0.0 if x = 0.0, and -1.0 if x invalid input: '<' 0. Returns NaN if x is NaN.

      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 value x.

      For a float value x, this method returns +1.0F if x > 0, 0.0F if x = 0.0F, and -1.0F if x invalid input: '<' 0. Returns NaN if x is NaN.

      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 value x.

      For an int value x, this method returns +1 if x > 0, 0 if x = 0, and -1 if x invalid input: '<' 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 value x.

      For a long value x, this method returns +1L if x > 0, 0L if x = 0, and -1L if x invalid input: '<' 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 value x.

      For a short value x, this method returns (short)(+1) if x > 0, (short)(0) if x = 0, and (short)(-1) if x invalid input: '<' 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 minuend
      y - the subtrahend
      Returns:
      the difference x-y
      Throws:
      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 value
      b - second value
      Returns:
      the difference a-b
      Throws:
      ArithmeticException - if the result can not be represented as an long
      Since:
      1.2
    • pow

      public static int pow(int k, int e) throws IllegalArgumentException
      Raise an int to an int power.
      Parameters:
      k - number to raise
      e - exponent (must be positive or null)
      Returns:
      ke
      Throws:
      IllegalArgumentException - if e is negative
    • pow

      public static int pow(int k, long e) throws IllegalArgumentException
      Raise an int to a long power.
      Parameters:
      k - number to raise
      e - exponent (must be positive or null)
      Returns:
      ke
      Throws:
      IllegalArgumentException - if e is negative
    • pow

      public static long pow(long k, int e) throws IllegalArgumentException
      Raise a long to an int power.
      Parameters:
      k - number to raise
      e - exponent (must be positive or null)
      Returns:
      ke
      Throws:
      IllegalArgumentException - if e is negative
    • pow

      public static long pow(long k, long e) throws IllegalArgumentException
      Raise a long to a long power.
      Parameters:
      k - number to raise
      e - exponent (must be positive or null)
      Returns:
      ke
      Throws:
      IllegalArgumentException - if e is negative
    • pow

      public static BigInteger pow(BigInteger k, int e) throws IllegalArgumentException
      Raise a BigInteger to an int power.
      Parameters:
      k - number to raise
      e - exponent (must be positive or null)
      Returns:
      ke
      Throws:
      IllegalArgumentException - if e is negative
    • pow

      public static BigInteger pow(BigInteger k, long e) throws IllegalArgumentException
      Raise a BigInteger to a long power.
      Parameters:
      k - number to raise
      e - exponent (must be positive or null)
      Returns:
      ke
      Throws:
      IllegalArgumentException - if e is negative
    • pow

      public static BigInteger pow(BigInteger k, BigInteger e) throws IllegalArgumentException
      Raise a BigInteger to a BigInteger power.
      Parameters:
      k - number to raise
      e - exponent (must be positive or null)
      Returns:
      ke
      Throws:
      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 point
      p2 - 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 point
      p2 - 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 point
      p2 - 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 point
      p2 - 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 point
      p2 - 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 point
      p2 - 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 new checkOrder method). To be removed in 3.0.
      Checks that the given array is sorted.
      Parameters:
      val - Values
      dir - 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:
      1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
      2. 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.
      3. 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.
      4. 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.
      5. 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