001/*
002 * Copyright (C) 2008 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.primitives;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkElementIndex;
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.base.Preconditions.checkPositionIndexes;
021import static java.lang.Double.NEGATIVE_INFINITY;
022import static java.lang.Double.POSITIVE_INFINITY;
023
024import com.google.common.annotations.Beta;
025import com.google.common.annotations.GwtCompatible;
026import com.google.common.annotations.GwtIncompatible;
027import com.google.common.base.Converter;
028import java.io.Serializable;
029import java.util.AbstractList;
030import java.util.Arrays;
031import java.util.Collection;
032import java.util.Collections;
033import java.util.Comparator;
034import java.util.List;
035import java.util.RandomAccess;
036import org.checkerframework.checker.nullness.compatqual.NullableDecl;
037
038/**
039 * Static utility methods pertaining to {@code double} primitives, that are not already found in
040 * either {@link Double} or {@link Arrays}.
041 *
042 * <p>See the Guava User Guide article on <a
043 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
044 *
045 * @author Kevin Bourrillion
046 * @since 1.0
047 */
048@GwtCompatible(emulated = true)
049public final class Doubles {
050  private Doubles() {}
051
052  /**
053   * The number of bytes required to represent a primitive {@code double} value.
054   *
055   * <p><b>Java 8 users:</b> use {@link Double#BYTES} instead.
056   *
057   * @since 10.0
058   */
059  public static final int BYTES = Double.SIZE / Byte.SIZE;
060
061  /**
062   * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Double)
063   * value).hashCode()}.
064   *
065   * <p><b>Java 8 users:</b> use {@link Double#hashCode(double)} instead.
066   *
067   * @param value a primitive {@code double} value
068   * @return a hash code for the value
069   */
070  public static int hashCode(double value) {
071    return ((Double) value).hashCode();
072    // TODO(kevinb): do it this way when we can (GWT problem):
073    // long bits = Double.doubleToLongBits(value);
074    // return (int) (bits ^ (bits >>> 32));
075  }
076
077  /**
078   * Compares the two specified {@code double} values. The sign of the value returned is the same as
079   * that of <code>((Double) a).{@linkplain Double#compareTo compareTo}(b)</code>. As with that
080   * method, {@code NaN} is treated as greater than all other values, and {@code 0.0 > -0.0}.
081   *
082   * <p><b>Note:</b> this method simply delegates to the JDK method {@link Double#compare}. It is
083   * provided for consistency with the other primitive types, whose compare methods were not added
084   * to the JDK until JDK 7.
085   *
086   * @param a the first {@code double} to compare
087   * @param b the second {@code double} to compare
088   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
089   *     greater than {@code b}; or zero if they are equal
090   */
091  public static int compare(double a, double b) {
092    return Double.compare(a, b);
093  }
094
095  /**
096   * Returns {@code true} if {@code value} represents a real number. This is equivalent to, but not
097   * necessarily implemented as, {@code !(Double.isInfinite(value) || Double.isNaN(value))}.
098   *
099   * <p><b>Java 8 users:</b> use {@link Double#isFinite(double)} instead.
100   *
101   * @since 10.0
102   */
103  public static boolean isFinite(double value) {
104    return NEGATIVE_INFINITY < value && value < POSITIVE_INFINITY;
105  }
106
107  /**
108   * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. Note
109   * that this always returns {@code false} when {@code target} is {@code NaN}.
110   *
111   * @param array an array of {@code double} values, possibly empty
112   * @param target a primitive {@code double} value
113   * @return {@code true} if {@code array[i] == target} for some value of {@code i}
114   */
115  public static boolean contains(double[] array, double target) {
116    for (double value : array) {
117      if (value == target) {
118        return true;
119      }
120    }
121    return false;
122  }
123
124  /**
125   * Returns the index of the first appearance of the value {@code target} in {@code array}. Note
126   * that this always returns {@code -1} when {@code target} is {@code NaN}.
127   *
128   * @param array an array of {@code double} values, possibly empty
129   * @param target a primitive {@code double} value
130   * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
131   *     such index exists.
132   */
133  public static int indexOf(double[] array, double target) {
134    return indexOf(array, target, 0, array.length);
135  }
136
137  // TODO(kevinb): consider making this public
138  private static int indexOf(double[] array, double target, int start, int end) {
139    for (int i = start; i < end; i++) {
140      if (array[i] == target) {
141        return i;
142      }
143    }
144    return -1;
145  }
146
147  /**
148   * Returns the start position of the first occurrence of the specified {@code target} within
149   * {@code array}, or {@code -1} if there is no such occurrence.
150   *
151   * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array,
152   * i, i + target.length)} contains exactly the same elements as {@code target}.
153   *
154   * <p>Note that this always returns {@code -1} when {@code target} contains {@code NaN}.
155   *
156   * @param array the array to search for the sequence {@code target}
157   * @param target the array to search for as a sub-sequence of {@code array}
158   */
159  public static int indexOf(double[] array, double[] target) {
160    checkNotNull(array, "array");
161    checkNotNull(target, "target");
162    if (target.length == 0) {
163      return 0;
164    }
165
166    outer:
167    for (int i = 0; i < array.length - target.length + 1; i++) {
168      for (int j = 0; j < target.length; j++) {
169        if (array[i + j] != target[j]) {
170          continue outer;
171        }
172      }
173      return i;
174    }
175    return -1;
176  }
177
178  /**
179   * Returns the index of the last appearance of the value {@code target} in {@code array}. Note
180   * that this always returns {@code -1} when {@code target} is {@code NaN}.
181   *
182   * @param array an array of {@code double} values, possibly empty
183   * @param target a primitive {@code double} value
184   * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no
185   *     such index exists.
186   */
187  public static int lastIndexOf(double[] array, double target) {
188    return lastIndexOf(array, target, 0, array.length);
189  }
190
191  // TODO(kevinb): consider making this public
192  private static int lastIndexOf(double[] array, double target, int start, int end) {
193    for (int i = end - 1; i >= start; i--) {
194      if (array[i] == target) {
195        return i;
196      }
197    }
198    return -1;
199  }
200
201  /**
202   * Returns the least value present in {@code array}, using the same rules of comparison as {@link
203   * Math#min(double, double)}.
204   *
205   * @param array a <i>nonempty</i> array of {@code double} values
206   * @return the value present in {@code array} that is less than or equal to every other value in
207   *     the array
208   * @throws IllegalArgumentException if {@code array} is empty
209   */
210  public static double min(double... array) {
211    checkArgument(array.length > 0);
212    double min = array[0];
213    for (int i = 1; i < array.length; i++) {
214      min = Math.min(min, array[i]);
215    }
216    return min;
217  }
218
219  /**
220   * Returns the greatest value present in {@code array}, using the same rules of comparison as
221   * {@link Math#max(double, double)}.
222   *
223   * @param array a <i>nonempty</i> array of {@code double} values
224   * @return the value present in {@code array} that is greater than or equal to every other value
225   *     in the array
226   * @throws IllegalArgumentException if {@code array} is empty
227   */
228  public static double max(double... array) {
229    checkArgument(array.length > 0);
230    double max = array[0];
231    for (int i = 1; i < array.length; i++) {
232      max = Math.max(max, array[i]);
233    }
234    return max;
235  }
236
237  /**
238   * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}.
239   *
240   * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned
241   * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code
242   * value} is greater than {@code max}, {@code max} is returned.
243   *
244   * @param value the {@code double} value to constrain
245   * @param min the lower bound (inclusive) of the range to constrain {@code value} to
246   * @param max the upper bound (inclusive) of the range to constrain {@code value} to
247   * @throws IllegalArgumentException if {@code min > max}
248   * @since 21.0
249   */
250  @Beta
251  public static double constrainToRange(double value, double min, double max) {
252    checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
253    return Math.min(Math.max(value, min), max);
254  }
255
256  /**
257   * Returns the values from each provided array combined into a single array. For example, {@code
258   * concat(new double[] {a, b}, new double[] {}, new double[] {c}} returns the array {@code {a, b,
259   * c}}.
260   *
261   * @param arrays zero or more {@code double} arrays
262   * @return a single array containing all the values from the source arrays, in order
263   */
264  public static double[] concat(double[]... arrays) {
265    int length = 0;
266    for (double[] array : arrays) {
267      length += array.length;
268    }
269    double[] result = new double[length];
270    int pos = 0;
271    for (double[] array : arrays) {
272      System.arraycopy(array, 0, result, pos, array.length);
273      pos += array.length;
274    }
275    return result;
276  }
277
278  private static final class DoubleConverter extends Converter<String, Double>
279      implements Serializable {
280    static final DoubleConverter INSTANCE = new DoubleConverter();
281
282    @Override
283    protected Double doForward(String value) {
284      return Double.valueOf(value);
285    }
286
287    @Override
288    protected String doBackward(Double value) {
289      return value.toString();
290    }
291
292    @Override
293    public String toString() {
294      return "Doubles.stringConverter()";
295    }
296
297    private Object readResolve() {
298      return INSTANCE;
299    }
300
301    private static final long serialVersionUID = 1;
302  }
303
304  /**
305   * Returns a serializable converter object that converts between strings and doubles using {@link
306   * Double#valueOf} and {@link Double#toString()}.
307   *
308   * @since 16.0
309   */
310  @Beta
311  public static Converter<String, Double> stringConverter() {
312    return DoubleConverter.INSTANCE;
313  }
314
315  /**
316   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
317   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
318   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
319   * returned, containing the values of {@code array}, and zeroes in the remaining places.
320   *
321   * @param array the source array
322   * @param minLength the minimum length the returned array must guarantee
323   * @param padding an extra amount to "grow" the array by if growth is necessary
324   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
325   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
326   *     minLength}
327   */
328  public static double[] ensureCapacity(double[] array, int minLength, int padding) {
329    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
330    checkArgument(padding >= 0, "Invalid padding: %s", padding);
331    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
332  }
333
334  /**
335   * Returns a string containing the supplied {@code double} values, converted to strings as
336   * specified by {@link Double#toString(double)}, and separated by {@code separator}. For example,
337   * {@code join("-", 1.0, 2.0, 3.0)} returns the string {@code "1.0-2.0-3.0"}.
338   *
339   * <p>Note that {@link Double#toString(double)} formats {@code double} differently in GWT
340   * sometimes. In the previous example, it returns the string {@code "1-2-3"}.
341   *
342   * @param separator the text that should appear between consecutive values in the resulting string
343   *     (but not at the start or end)
344   * @param array an array of {@code double} values, possibly empty
345   */
346  public static String join(String separator, double... array) {
347    checkNotNull(separator);
348    if (array.length == 0) {
349      return "";
350    }
351
352    // For pre-sizing a builder, just get the right order of magnitude
353    StringBuilder builder = new StringBuilder(array.length * 12);
354    builder.append(array[0]);
355    for (int i = 1; i < array.length; i++) {
356      builder.append(separator).append(array[i]);
357    }
358    return builder.toString();
359  }
360
361  /**
362   * Returns a comparator that compares two {@code double} arrays <a
363   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
364   * compares, using {@link #compare(double, double)}), the first pair of values that follow any
365   * common prefix, or when one array is a prefix of the other, treats the shorter array as the
366   * lesser. For example, {@code [] < [1.0] < [1.0, 2.0] < [2.0]}.
367   *
368   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
369   * support only identity equality), but it is consistent with {@link Arrays#equals(double[],
370   * double[])}.
371   *
372   * @since 2.0
373   */
374  public static Comparator<double[]> lexicographicalComparator() {
375    return LexicographicalComparator.INSTANCE;
376  }
377
378  private enum LexicographicalComparator implements Comparator<double[]> {
379    INSTANCE;
380
381    @Override
382    public int compare(double[] left, double[] right) {
383      int minLength = Math.min(left.length, right.length);
384      for (int i = 0; i < minLength; i++) {
385        int result = Double.compare(left[i], right[i]);
386        if (result != 0) {
387          return result;
388        }
389      }
390      return left.length - right.length;
391    }
392
393    @Override
394    public String toString() {
395      return "Doubles.lexicographicalComparator()";
396    }
397  }
398
399  /**
400   * Sorts the elements of {@code array} in descending order.
401   *
402   * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats
403   * all NaN values as equal and 0.0 as greater than -0.0.
404   *
405   * @since 23.1
406   */
407  public static void sortDescending(double[] array) {
408    checkNotNull(array);
409    sortDescending(array, 0, array.length);
410  }
411
412  /**
413   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
414   * exclusive in descending order.
415   *
416   * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats
417   * all NaN values as equal and 0.0 as greater than -0.0.
418   *
419   * @since 23.1
420   */
421  public static void sortDescending(double[] array, int fromIndex, int toIndex) {
422    checkNotNull(array);
423    checkPositionIndexes(fromIndex, toIndex, array.length);
424    Arrays.sort(array, fromIndex, toIndex);
425    reverse(array, fromIndex, toIndex);
426  }
427
428  /**
429   * Reverses the elements of {@code array}. This is equivalent to {@code
430   * Collections.reverse(Doubles.asList(array))}, but is likely to be more efficient.
431   *
432   * @since 23.1
433   */
434  public static void reverse(double[] array) {
435    checkNotNull(array);
436    reverse(array, 0, array.length);
437  }
438
439  /**
440   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
441   * exclusive. This is equivalent to {@code
442   * Collections.reverse(Doubles.asList(array).subList(fromIndex, toIndex))}, but is likely to be
443   * more efficient.
444   *
445   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
446   *     {@code toIndex > fromIndex}
447   * @since 23.1
448   */
449  public static void reverse(double[] array, int fromIndex, int toIndex) {
450    checkNotNull(array);
451    checkPositionIndexes(fromIndex, toIndex, array.length);
452    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
453      double tmp = array[i];
454      array[i] = array[j];
455      array[j] = tmp;
456    }
457  }
458
459  /**
460   * Returns an array containing each value of {@code collection}, converted to a {@code double}
461   * value in the manner of {@link Number#doubleValue}.
462   *
463   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
464   * Calling this method is as thread-safe as calling that method.
465   *
466   * @param collection a collection of {@code Number} instances
467   * @return an array containing the same values as {@code collection}, in the same order, converted
468   *     to primitives
469   * @throws NullPointerException if {@code collection} or any of its elements is null
470   * @since 1.0 (parameter was {@code Collection<Double>} before 12.0)
471   */
472  public static double[] toArray(Collection<? extends Number> collection) {
473    if (collection instanceof DoubleArrayAsList) {
474      return ((DoubleArrayAsList) collection).toDoubleArray();
475    }
476
477    Object[] boxedArray = collection.toArray();
478    int len = boxedArray.length;
479    double[] array = new double[len];
480    for (int i = 0; i < len; i++) {
481      // checkNotNull for GWT (do not optimize)
482      array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue();
483    }
484    return array;
485  }
486
487  /**
488   * Returns a fixed-size list backed by the specified array, similar to {@link
489   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
490   * set a value to {@code null} will result in a {@link NullPointerException}.
491   *
492   * <p>The returned list maintains the values, but not the identities, of {@code Double} objects
493   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
494   * the returned list is unspecified.
495   *
496   * <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN}
497   * is used as a parameter to any of its methods.
498   *
499   * <p><b>Note:</b> when possible, you should represent your data as an {@link
500   * ImmutableDoubleArray} instead, which has an {@link ImmutableDoubleArray#asList asList} view.
501   *
502   * @param backingArray the array to back the list
503   * @return a list view of the array
504   */
505  public static List<Double> asList(double... backingArray) {
506    if (backingArray.length == 0) {
507      return Collections.emptyList();
508    }
509    return new DoubleArrayAsList(backingArray);
510  }
511
512  @GwtCompatible
513  private static class DoubleArrayAsList extends AbstractList<Double>
514      implements RandomAccess, Serializable {
515    final double[] array;
516    final int start;
517    final int end;
518
519    DoubleArrayAsList(double[] array) {
520      this(array, 0, array.length);
521    }
522
523    DoubleArrayAsList(double[] array, int start, int end) {
524      this.array = array;
525      this.start = start;
526      this.end = end;
527    }
528
529    @Override
530    public int size() {
531      return end - start;
532    }
533
534    @Override
535    public boolean isEmpty() {
536      return false;
537    }
538
539    @Override
540    public Double get(int index) {
541      checkElementIndex(index, size());
542      return array[start + index];
543    }
544
545    @Override
546    public boolean contains(Object target) {
547      // Overridden to prevent a ton of boxing
548      return (target instanceof Double)
549          && Doubles.indexOf(array, (Double) target, start, end) != -1;
550    }
551
552    @Override
553    public int indexOf(Object target) {
554      // Overridden to prevent a ton of boxing
555      if (target instanceof Double) {
556        int i = Doubles.indexOf(array, (Double) target, start, end);
557        if (i >= 0) {
558          return i - start;
559        }
560      }
561      return -1;
562    }
563
564    @Override
565    public int lastIndexOf(Object target) {
566      // Overridden to prevent a ton of boxing
567      if (target instanceof Double) {
568        int i = Doubles.lastIndexOf(array, (Double) target, start, end);
569        if (i >= 0) {
570          return i - start;
571        }
572      }
573      return -1;
574    }
575
576    @Override
577    public Double set(int index, Double element) {
578      checkElementIndex(index, size());
579      double oldValue = array[start + index];
580      // checkNotNull for GWT (do not optimize)
581      array[start + index] = checkNotNull(element);
582      return oldValue;
583    }
584
585    @Override
586    public List<Double> subList(int fromIndex, int toIndex) {
587      int size = size();
588      checkPositionIndexes(fromIndex, toIndex, size);
589      if (fromIndex == toIndex) {
590        return Collections.emptyList();
591      }
592      return new DoubleArrayAsList(array, start + fromIndex, start + toIndex);
593    }
594
595    @Override
596    public boolean equals(@NullableDecl Object object) {
597      if (object == this) {
598        return true;
599      }
600      if (object instanceof DoubleArrayAsList) {
601        DoubleArrayAsList that = (DoubleArrayAsList) object;
602        int size = size();
603        if (that.size() != size) {
604          return false;
605        }
606        for (int i = 0; i < size; i++) {
607          if (array[start + i] != that.array[that.start + i]) {
608            return false;
609          }
610        }
611        return true;
612      }
613      return super.equals(object);
614    }
615
616    @Override
617    public int hashCode() {
618      int result = 1;
619      for (int i = start; i < end; i++) {
620        result = 31 * result + Doubles.hashCode(array[i]);
621      }
622      return result;
623    }
624
625    @Override
626    public String toString() {
627      StringBuilder builder = new StringBuilder(size() * 12);
628      builder.append('[').append(array[start]);
629      for (int i = start + 1; i < end; i++) {
630        builder.append(", ").append(array[i]);
631      }
632      return builder.append(']').toString();
633    }
634
635    double[] toDoubleArray() {
636      return Arrays.copyOfRange(array, start, end);
637    }
638
639    private static final long serialVersionUID = 0;
640  }
641
642  /**
643   * This is adapted from the regex suggested by {@link Double#valueOf(String)} for prevalidating
644   * inputs. All valid inputs must pass this regex, but it's semantically fine if not all inputs
645   * that pass this regex are valid -- only a performance hit is incurred, not a semantics bug.
646   */
647  @GwtIncompatible // regular expressions
648  static final
649  java.util.regex.Pattern
650      FLOATING_POINT_PATTERN = fpPattern();
651
652  @GwtIncompatible // regular expressions
653  private static
654  java.util.regex.Pattern
655      fpPattern() {
656    /*
657     * We use # instead of * for possessive quantifiers. This lets us strip them out when building
658     * the regex for RE2 (which doesn't support them) but leave them in when building it for
659     * java.util.regex (where we want them in order to avoid catastrophic backtracking).
660     */
661    String decimal = "(?:\\d+#(?:\\.\\d*#)?|\\.\\d+#)";
662    String completeDec = decimal + "(?:[eE][+-]?\\d+#)?[fFdD]?";
663    String hex = "(?:[0-9a-fA-F]+#(?:\\.[0-9a-fA-F]*#)?|\\.[0-9a-fA-F]+#)";
664    String completeHex = "0[xX]" + hex + "[pP][+-]?\\d+#[fFdD]?";
665    String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")";
666    fpPattern =
667        fpPattern.replace(
668            "#",
669            "+"
670            );
671    return
672    java.util.regex.Pattern
673        .compile(fpPattern);
674  }
675
676  /**
677   * Parses the specified string as a double-precision floating point value. The ASCII character
678   * {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign.
679   *
680   * <p>Unlike {@link Double#parseDouble(String)}, this method returns {@code null} instead of
681   * throwing an exception if parsing fails. Valid inputs are exactly those accepted by {@link
682   * Double#valueOf(String)}, except that leading and trailing whitespace is not permitted.
683   *
684   * <p>This implementation is likely to be faster than {@code Double.parseDouble} if many failures
685   * are expected.
686   *
687   * @param string the string representation of a {@code double} value
688   * @return the floating point value represented by {@code string}, or {@code null} if {@code
689   *     string} has a length of zero or cannot be parsed as a {@code double} value
690   * @throws NullPointerException if {@code string} is {@code null}
691   * @since 14.0
692   */
693  @Beta
694  @GwtIncompatible // regular expressions
695  @NullableDecl
696  public static Double tryParse(String string) {
697    if (FLOATING_POINT_PATTERN.matcher(string).matches()) {
698      // TODO(lowasser): could be potentially optimized, but only with
699      // extensive testing
700      try {
701        return Double.parseDouble(string);
702      } catch (NumberFormatException e) {
703        // Double.parseDouble has changed specs several times, so fall through
704        // gracefully
705      }
706    }
707    return null;
708  }
709}