org.elasticsearch.common.math
Class MathUtils

java.lang.Object
  extended by org.elasticsearch.common.math.MathUtils

public final class MathUtils
extends Object

Some useful additions to the built-in functions in Math.

Version:
$Revision: 927249 $ $Date: 2010-03-24 21:06:51 -0400 (Wed, 24 Mar 2010) $

Field Summary
static double EPSILON
          Smallest positive number such that 1 - EPSILON is not numerically equal to 1.
static double SAFE_MIN
          Safe minimum, such that 1 / SAFE_MIN does not overflow.
static double TWO_PI
          2 π.
 
Method Summary
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 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.
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, int 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 equals
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 iff both arguments are equal or within the range of allowed error (inclusive).
static boolean equals(double x, double y, int maxUlps)
          Returns true iff both arguments are equal or within the range of allowed error (inclusive).
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 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)
          Get the next machine representable number after a number, moving in the direction of another number.
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 BigInteger pow(BigInteger k, BigInteger e)
          Raise a BigInteger to a BigInteger 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 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 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 scalb(double d, int scaleFactor)
          Scale a number by 2scaleFactor.
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
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

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 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:

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:

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:

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

public static boolean equals(double x,
                             double y)
Returns true iff both arguments are NaN or neither is NaN and they are equal

Parameters:
x - first value
y - second value
Returns:
true if the values are equal or both are NaN

equals

public static boolean equals(double x,
                             double y,
                             double eps)
Returns true iff both arguments are equal or within the range of allowed error (inclusive).

Two NaNs are considered equals, as are two infinities with same sign.

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

equals

public static boolean equals(double x,
                             double y,
                             int maxUlps)
Returns true iff both arguments are equal or within the range of allowed error (inclusive). 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 less than maxUlps floating point values between x and y

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 equals

Parameters:
x - first array
y - second array
Returns:
true if the values are both null or have same dimension and equal elements
Since:
1.2

factorial

public static long factorial(int n)
Returns n!. Shorthand for n Factorial, the product of the numbers 1,...,n.

Preconditions:

Parameters:
n - argument
Returns:
n!
Throws:
ArithmeticException - if the result is too large to be represented by a long integer.
IllegalArgumentException - if n < 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:

Parameters:
n - argument
Returns:
n!
Throws:
IllegalArgumentException - if n < 0

factorialLog

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

Preconditions:

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:

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:

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 < 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. 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 < 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 < 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 lcm(a,b) = (a / gcd(a,b)) * b.

Special cases:

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:

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

public static double nextAfter(double d,
                               double direction)
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

public static double scalb(double d,
                           int scaleFactor)
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 sould 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, Math.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 < 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 < 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 < 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 < 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 < 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 < 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,
                              int dir,
                              boolean strict)
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:
IllegalArgumentException - if the array is not sorted.


Copyright © 2009-2012. All Rights Reserved.