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