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