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