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