001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.math;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.math.DoubleUtils.IMPLICIT_BIT;
019import static com.google.common.math.DoubleUtils.SIGNIFICAND_BITS;
020import static com.google.common.math.DoubleUtils.getSignificand;
021import static com.google.common.math.DoubleUtils.isFinite;
022import static com.google.common.math.DoubleUtils.isNormal;
023import static com.google.common.math.DoubleUtils.scaleNormalize;
024import static com.google.common.math.MathPreconditions.checkInRangeForRoundingInputs;
025import static com.google.common.math.MathPreconditions.checkNonNegative;
026import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
027import static java.lang.Math.abs;
028import static java.lang.Math.copySign;
029import static java.lang.Math.getExponent;
030import static java.lang.Math.log;
031import static java.lang.Math.rint;
032
033import com.google.common.annotations.GwtCompatible;
034import com.google.common.annotations.GwtIncompatible;
035import com.google.common.annotations.VisibleForTesting;
036import com.google.errorprone.annotations.CanIgnoreReturnValue;
037import java.math.BigInteger;
038import java.math.RoundingMode;
039import java.util.Iterator;
040
041/**
042 * A class for arithmetic on doubles that is not covered by {@link java.lang.Math}.
043 *
044 * @author Louis Wasserman
045 * @since 11.0
046 */
047@GwtCompatible(emulated = true)
048@ElementTypesAreNonnullByDefault
049public final class DoubleMath {
050  /*
051   * This method returns a value y such that rounding y DOWN (towards zero) gives the same result as
052   * rounding x according to the specified mode.
053   */
054  @GwtIncompatible // #isMathematicalInteger, com.google.common.math.DoubleUtils
055  static double roundIntermediate(double x, RoundingMode mode) {
056    if (!isFinite(x)) {
057      throw new ArithmeticException("input is infinite or NaN");
058    }
059    switch (mode) {
060      case UNNECESSARY:
061        checkRoundingUnnecessary(isMathematicalInteger(x));
062        return x;
063
064      case FLOOR:
065        if (x >= 0.0 || isMathematicalInteger(x)) {
066          return x;
067        } else {
068          return (long) x - 1;
069        }
070
071      case CEILING:
072        if (x <= 0.0 || isMathematicalInteger(x)) {
073          return x;
074        } else {
075          return (long) x + 1;
076        }
077
078      case DOWN:
079        return x;
080
081      case UP:
082        if (isMathematicalInteger(x)) {
083          return x;
084        } else {
085          return (long) x + (x > 0 ? 1 : -1);
086        }
087
088      case HALF_EVEN:
089        return rint(x);
090
091      case HALF_UP:
092        {
093          double z = rint(x);
094          if (abs(x - z) == 0.5) {
095            return x + copySign(0.5, x);
096          } else {
097            return z;
098          }
099        }
100
101      case HALF_DOWN:
102        {
103          double z = rint(x);
104          if (abs(x - z) == 0.5) {
105            return x;
106          } else {
107            return z;
108          }
109        }
110
111      default:
112        throw new AssertionError();
113    }
114  }
115
116  /**
117   * Returns the {@code int} value that is equal to {@code x} rounded with the specified rounding
118   * mode, if possible.
119   *
120   * @throws ArithmeticException if
121   *     <ul>
122   *       <li>{@code x} is infinite or NaN
123   *       <li>{@code x}, after being rounded to a mathematical integer using the specified rounding
124   *           mode, is either less than {@code Integer.MIN_VALUE} or greater than {@code
125   *           Integer.MAX_VALUE}
126   *       <li>{@code x} is not a mathematical integer and {@code mode} is {@link
127   *           RoundingMode#UNNECESSARY}
128   *     </ul>
129   */
130  @GwtIncompatible // #roundIntermediate
131  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
132  @SuppressWarnings("ShortCircuitBoolean")
133  public static int roundToInt(double x, RoundingMode mode) {
134    double z = roundIntermediate(x, mode);
135    checkInRangeForRoundingInputs(
136        z > MIN_INT_AS_DOUBLE - 1.0 & z < MAX_INT_AS_DOUBLE + 1.0, x, mode);
137    return (int) z;
138  }
139
140  private static final double MIN_INT_AS_DOUBLE = -0x1p31;
141  private static final double MAX_INT_AS_DOUBLE = 0x1p31 - 1.0;
142
143  /**
144   * Returns the {@code long} value that is equal to {@code x} rounded with the specified rounding
145   * mode, if possible.
146   *
147   * @throws ArithmeticException if
148   *     <ul>
149   *       <li>{@code x} is infinite or NaN
150   *       <li>{@code x}, after being rounded to a mathematical integer using the specified rounding
151   *           mode, is either less than {@code Long.MIN_VALUE} or greater than {@code
152   *           Long.MAX_VALUE}
153   *       <li>{@code x} is not a mathematical integer and {@code mode} is {@link
154   *           RoundingMode#UNNECESSARY}
155   *     </ul>
156   */
157  @GwtIncompatible // #roundIntermediate
158  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
159  @SuppressWarnings("ShortCircuitBoolean")
160  public static long roundToLong(double x, RoundingMode mode) {
161    double z = roundIntermediate(x, mode);
162    checkInRangeForRoundingInputs(
163        MIN_LONG_AS_DOUBLE - z < 1.0 & z < MAX_LONG_AS_DOUBLE_PLUS_ONE, x, mode);
164    return (long) z;
165  }
166
167  private static final double MIN_LONG_AS_DOUBLE = -0x1p63;
168  /*
169   * We cannot store Long.MAX_VALUE as a double without losing precision. Instead, we store
170   * Long.MAX_VALUE + 1 == -Long.MIN_VALUE, and then offset all comparisons by 1.
171   */
172  private static final double MAX_LONG_AS_DOUBLE_PLUS_ONE = 0x1p63;
173
174  /**
175   * Returns the {@code BigInteger} value that is equal to {@code x} rounded with the specified
176   * rounding mode, if possible.
177   *
178   * @throws ArithmeticException if
179   *     <ul>
180   *       <li>{@code x} is infinite or NaN
181   *       <li>{@code x} is not a mathematical integer and {@code mode} is {@link
182   *           RoundingMode#UNNECESSARY}
183   *     </ul>
184   */
185  // #roundIntermediate, java.lang.Math.getExponent, com.google.common.math.DoubleUtils
186  @GwtIncompatible
187  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
188  @SuppressWarnings("ShortCircuitBoolean")
189  public static BigInteger roundToBigInteger(double x, RoundingMode mode) {
190    x = roundIntermediate(x, mode);
191    if (MIN_LONG_AS_DOUBLE - x < 1.0 & x < MAX_LONG_AS_DOUBLE_PLUS_ONE) {
192      return BigInteger.valueOf((long) x);
193    }
194    int exponent = getExponent(x);
195    long significand = getSignificand(x);
196    BigInteger result = BigInteger.valueOf(significand).shiftLeft(exponent - SIGNIFICAND_BITS);
197    return (x < 0) ? result.negate() : result;
198  }
199
200  /**
201   * Returns {@code true} if {@code x} is exactly equal to {@code 2^k} for some finite integer
202   * {@code k}.
203   */
204  @GwtIncompatible // com.google.common.math.DoubleUtils
205  public static boolean isPowerOfTwo(double x) {
206    if (x > 0.0 && isFinite(x)) {
207      long significand = getSignificand(x);
208      return (significand & (significand - 1)) == 0;
209    }
210    return false;
211  }
212
213  /**
214   * Returns the base 2 logarithm of a double value.
215   *
216   * <p>Special cases:
217   *
218   * <ul>
219   *   <li>If {@code x} is NaN or less than zero, the result is NaN.
220   *   <li>If {@code x} is positive infinity, the result is positive infinity.
221   *   <li>If {@code x} is positive or negative zero, the result is negative infinity.
222   * </ul>
223   *
224   * <p>The computed result is within 1 ulp of the exact result.
225   *
226   * <p>If the result of this method will be immediately rounded to an {@code int}, {@link
227   * #log2(double, RoundingMode)} is faster.
228   */
229  public static double log2(double x) {
230    return log(x) / LN_2; // surprisingly within 1 ulp according to tests
231  }
232
233  /**
234   * Returns the base 2 logarithm of a double value, rounded with the specified rounding mode to an
235   * {@code int}.
236   *
237   * <p>Regardless of the rounding mode, this is faster than {@code (int) log2(x)}.
238   *
239   * @throws IllegalArgumentException if {@code x <= 0.0}, {@code x} is NaN, or {@code x} is
240   *     infinite
241   */
242  @GwtIncompatible // java.lang.Math.getExponent, com.google.common.math.DoubleUtils
243  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
244  @SuppressWarnings({"fallthrough", "ShortCircuitBoolean"})
245  public static int log2(double x, RoundingMode mode) {
246    checkArgument(x > 0.0 && isFinite(x), "x must be positive and finite");
247    int exponent = getExponent(x);
248    if (!isNormal(x)) {
249      return log2(x * IMPLICIT_BIT, mode) - SIGNIFICAND_BITS;
250      // Do the calculation on a normal value.
251    }
252    // x is positive, finite, and normal
253    boolean increment;
254    switch (mode) {
255      case UNNECESSARY:
256        checkRoundingUnnecessary(isPowerOfTwo(x));
257        // fall through
258      case FLOOR:
259        increment = false;
260        break;
261      case CEILING:
262        increment = !isPowerOfTwo(x);
263        break;
264      case DOWN:
265        increment = exponent < 0 & !isPowerOfTwo(x);
266        break;
267      case UP:
268        increment = exponent >= 0 & !isPowerOfTwo(x);
269        break;
270      case HALF_DOWN:
271      case HALF_EVEN:
272      case HALF_UP:
273        double xScaled = scaleNormalize(x);
274        // sqrt(2) is irrational, and the spec is relative to the "exact numerical result,"
275        // so log2(x) is never exactly exponent + 0.5.
276        increment = (xScaled * xScaled) > 2.0;
277        break;
278      default:
279        throw new AssertionError();
280    }
281    return increment ? exponent + 1 : exponent;
282  }
283
284  private static final double LN_2 = log(2);
285
286  /**
287   * Returns {@code true} if {@code x} represents a mathematical integer.
288   *
289   * <p>This is equivalent to, but not necessarily implemented as, the expression {@code
290   * !Double.isNaN(x) && !Double.isInfinite(x) && x == Math.rint(x)}.
291   */
292  @GwtIncompatible // java.lang.Math.getExponent, com.google.common.math.DoubleUtils
293  public static boolean isMathematicalInteger(double x) {
294    return isFinite(x)
295        && (x == 0.0
296            || SIGNIFICAND_BITS - Long.numberOfTrailingZeros(getSignificand(x)) <= getExponent(x));
297  }
298
299  /**
300   * Returns {@code n!}, that is, the product of the first {@code n} positive integers, {@code 1} if
301   * {@code n == 0}, or {@code n!}, or {@link Double#POSITIVE_INFINITY} if {@code n! >
302   * Double.MAX_VALUE}.
303   *
304   * <p>The result is within 1 ulp of the true value.
305   *
306   * @throws IllegalArgumentException if {@code n < 0}
307   */
308  public static double factorial(int n) {
309    checkNonNegative("n", n);
310    if (n > MAX_FACTORIAL) {
311      return Double.POSITIVE_INFINITY;
312    } else {
313      // Multiplying the last (n & 0xf) values into their own accumulator gives a more accurate
314      // result than multiplying by everySixteenthFactorial[n >> 4] directly.
315      double accum = 1.0;
316      for (int i = 1 + (n & ~0xf); i <= n; i++) {
317        accum *= i;
318      }
319      return accum * everySixteenthFactorial[n >> 4];
320    }
321  }
322
323  @VisibleForTesting static final int MAX_FACTORIAL = 170;
324
325  @VisibleForTesting
326  static final double[] everySixteenthFactorial = {
327    0x1.0p0,
328    0x1.30777758p44,
329    0x1.956ad0aae33a4p117,
330    0x1.ee69a78d72cb6p202,
331    0x1.fe478ee34844ap295,
332    0x1.c619094edabffp394,
333    0x1.3638dd7bd6347p498,
334    0x1.7cac197cfe503p605,
335    0x1.1e5dfc140e1e5p716,
336    0x1.8ce85fadb707ep829,
337    0x1.95d5f3d928edep945
338  };
339
340  /**
341   * Returns {@code true} if {@code a} and {@code b} are within {@code tolerance} of each other.
342   *
343   * <p>Technically speaking, this is equivalent to {@code Math.abs(a - b) <= tolerance ||
344   * Double.valueOf(a).equals(Double.valueOf(b))}.
345   *
346   * <p>Notable special cases include:
347   *
348   * <ul>
349   *   <li>All NaNs are fuzzily equal.
350   *   <li>If {@code a == b}, then {@code a} and {@code b} are always fuzzily equal.
351   *   <li>Positive and negative zero are always fuzzily equal.
352   *   <li>If {@code tolerance} is zero, and neither {@code a} nor {@code b} is NaN, then {@code a}
353   *       and {@code b} are fuzzily equal if and only if {@code a == b}.
354   *   <li>With {@link Double#POSITIVE_INFINITY} tolerance, all non-NaN values are fuzzily equal.
355   *   <li>With finite tolerance, {@code Double.POSITIVE_INFINITY} and {@code
356   *       Double.NEGATIVE_INFINITY} are fuzzily equal only to themselves.
357   * </ul>
358   *
359   * <p>This is reflexive and symmetric, but <em>not</em> transitive, so it is <em>not</em> an
360   * equivalence relation and <em>not</em> suitable for use in {@link Object#equals}
361   * implementations.
362   *
363   * @throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN
364   * @since 13.0
365   */
366  public static boolean fuzzyEquals(double a, double b, double tolerance) {
367    MathPreconditions.checkNonNegative("tolerance", tolerance);
368    return Math.copySign(a - b, 1.0) <= tolerance
369        // copySign(x, 1.0) is a branch-free version of abs(x), but with different NaN semantics
370        || (a == b) // needed to ensure that infinities equal themselves
371        || (Double.isNaN(a) && Double.isNaN(b));
372  }
373
374  /**
375   * Compares {@code a} and {@code b} "fuzzily," with a tolerance for nearly-equal values.
376   *
377   * <p>This method is equivalent to {@code fuzzyEquals(a, b, tolerance) ? 0 : Double.compare(a,
378   * b)}. In particular, like {@link Double#compare(double, double)}, it treats all NaN values as
379   * equal and greater than all other values (including {@link Double#POSITIVE_INFINITY}).
380   *
381   * <p>This is <em>not</em> a total ordering and is <em>not</em> suitable for use in {@link
382   * Comparable#compareTo} implementations. In particular, it is not transitive.
383   *
384   * @throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN
385   * @since 13.0
386   */
387  public static int fuzzyCompare(double a, double b, double tolerance) {
388    if (fuzzyEquals(a, b, tolerance)) {
389      return 0;
390    } else if (a < b) {
391      return -1;
392    } else if (a > b) {
393      return 1;
394    } else {
395      return Boolean.compare(Double.isNaN(a), Double.isNaN(b));
396    }
397  }
398
399  /**
400   * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of
401   * {@code values}.
402   *
403   * <p>If these values are a sample drawn from a population, this is also an unbiased estimator of
404   * the arithmetic mean of the population.
405   *
406   * @param values a nonempty series of values
407   * @throws IllegalArgumentException if {@code values} is empty or contains any non-finite value
408   * @deprecated Use {@link Stats#meanOf} instead, noting the less strict handling of non-finite
409   *     values.
410   */
411  @Deprecated
412  // com.google.common.math.DoubleUtils
413  @GwtIncompatible
414  public static double mean(double... values) {
415    checkArgument(values.length > 0, "Cannot take mean of 0 values");
416    long count = 1;
417    double mean = checkFinite(values[0]);
418    for (int index = 1; index < values.length; ++index) {
419      checkFinite(values[index]);
420      count++;
421      // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15)
422      mean += (values[index] - mean) / count;
423    }
424    return mean;
425  }
426
427  /**
428   * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of
429   * {@code values}.
430   *
431   * <p>If these values are a sample drawn from a population, this is also an unbiased estimator of
432   * the arithmetic mean of the population.
433   *
434   * @param values a nonempty series of values
435   * @throws IllegalArgumentException if {@code values} is empty
436   * @deprecated Use {@link Stats#meanOf} instead, noting the less strict handling of non-finite
437   *     values.
438   */
439  @Deprecated
440  public static double mean(int... values) {
441    checkArgument(values.length > 0, "Cannot take mean of 0 values");
442    // The upper bound on the length of an array and the bounds on the int values mean that, in
443    // this case only, we can compute the sum as a long without risking overflow or loss of
444    // precision. So we do that, as it's slightly quicker than the Knuth algorithm.
445    long sum = 0;
446    for (int index = 0; index < values.length; ++index) {
447      sum += values[index];
448    }
449    return (double) sum / values.length;
450  }
451
452  /**
453   * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of
454   * {@code values}.
455   *
456   * <p>If these values are a sample drawn from a population, this is also an unbiased estimator of
457   * the arithmetic mean of the population.
458   *
459   * @param values a nonempty series of values, which will be converted to {@code double} values
460   *     (this may cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15))
461   * @throws IllegalArgumentException if {@code values} is empty
462   * @deprecated Use {@link Stats#meanOf} instead, noting the less strict handling of non-finite
463   *     values.
464   */
465  @Deprecated
466  public static double mean(long... values) {
467    checkArgument(values.length > 0, "Cannot take mean of 0 values");
468    long count = 1;
469    double mean = values[0];
470    for (int index = 1; index < values.length; ++index) {
471      count++;
472      // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15)
473      mean += (values[index] - mean) / count;
474    }
475    return mean;
476  }
477
478  /**
479   * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of
480   * {@code values}.
481   *
482   * <p>If these values are a sample drawn from a population, this is also an unbiased estimator of
483   * the arithmetic mean of the population.
484   *
485   * @param values a nonempty series of values, which will be converted to {@code double} values
486   *     (this may cause loss of precision)
487   * @throws IllegalArgumentException if {@code values} is empty or contains any non-finite value
488   * @deprecated Use {@link Stats#meanOf} instead, noting the less strict handling of non-finite
489   *     values.
490   */
491  @Deprecated
492  // com.google.common.math.DoubleUtils
493  @GwtIncompatible
494  public static double mean(Iterable<? extends Number> values) {
495    return mean(values.iterator());
496  }
497
498  /**
499   * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of
500   * {@code values}.
501   *
502   * <p>If these values are a sample drawn from a population, this is also an unbiased estimator of
503   * the arithmetic mean of the population.
504   *
505   * @param values a nonempty series of values, which will be converted to {@code double} values
506   *     (this may cause loss of precision)
507   * @throws IllegalArgumentException if {@code values} is empty or contains any non-finite value
508   * @deprecated Use {@link Stats#meanOf} instead, noting the less strict handling of non-finite
509   *     values.
510   */
511  @Deprecated
512  // com.google.common.math.DoubleUtils
513  @GwtIncompatible
514  public static double mean(Iterator<? extends Number> values) {
515    checkArgument(values.hasNext(), "Cannot take mean of 0 values");
516    long count = 1;
517    double mean = checkFinite(values.next().doubleValue());
518    while (values.hasNext()) {
519      double value = checkFinite(values.next().doubleValue());
520      count++;
521      // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15)
522      mean += (value - mean) / count;
523    }
524    return mean;
525  }
526
527  @GwtIncompatible // com.google.common.math.DoubleUtils
528  @CanIgnoreReturnValue
529  private static double checkFinite(double argument) {
530    checkArgument(isFinite(argument));
531    return argument;
532  }
533
534  private DoubleMath() {}
535}