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   * Returns an array containing each value of {@code collection}, converted to a {@code double}
405   * value in the manner of {@link Number#doubleValue}.
406   *
407   * <p>Elements are copied from the argument collection as if by {@code
408   * collection.toArray()}. Calling this method is as thread-safe as calling that method.
409   *
410   * @param collection a collection of {@code Number} instances
411   * @return an array containing the same values as {@code collection}, in the same order, converted
412   *     to primitives
413   * @throws NullPointerException if {@code collection} or any of its elements is null
414   * @since 1.0 (parameter was {@code Collection<Double>} before 12.0)
415   */
416  public static double[] toArray(Collection<? extends Number> collection) {
417    if (collection instanceof DoubleArrayAsList) {
418      return ((DoubleArrayAsList) collection).toDoubleArray();
419    }
420
421    Object[] boxedArray = collection.toArray();
422    int len = boxedArray.length;
423    double[] array = new double[len];
424    for (int i = 0; i < len; i++) {
425      // checkNotNull for GWT (do not optimize)
426      array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue();
427    }
428    return array;
429  }
430
431  /**
432   * Returns a fixed-size list backed by the specified array, similar to
433   * {@link Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any
434   * attempt to set a value to {@code null} will result in a {@link NullPointerException}.
435   *
436   * <p>The returned list maintains the values, but not the identities, of {@code Double} objects
437   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
438   * the returned list is unspecified.
439   *
440   * <p>The returned list may have unexpected behavior if it contains {@code
441   * NaN}, or if {@code NaN} is used as a parameter to any of its methods.
442   *
443   * @param backingArray the array to back the list
444   * @return a list view of the array
445   */
446  public static List<Double> asList(double... backingArray) {
447    if (backingArray.length == 0) {
448      return Collections.emptyList();
449    }
450    return new DoubleArrayAsList(backingArray);
451  }
452
453  @GwtCompatible
454  private static class DoubleArrayAsList extends AbstractList<Double>
455      implements RandomAccess, Serializable {
456    final double[] array;
457    final int start;
458    final int end;
459
460    DoubleArrayAsList(double[] array) {
461      this(array, 0, array.length);
462    }
463
464    DoubleArrayAsList(double[] array, int start, int end) {
465      this.array = array;
466      this.start = start;
467      this.end = end;
468    }
469
470    @Override
471    public int size() {
472      return end - start;
473    }
474
475    @Override
476    public boolean isEmpty() {
477      return false;
478    }
479
480    @Override
481    public Double get(int index) {
482      checkElementIndex(index, size());
483      return array[start + index];
484    }
485
486    @Override
487    public boolean contains(Object target) {
488      // Overridden to prevent a ton of boxing
489      return (target instanceof Double)
490          && Doubles.indexOf(array, (Double) target, start, end) != -1;
491    }
492
493    @Override
494    public int indexOf(Object target) {
495      // Overridden to prevent a ton of boxing
496      if (target instanceof Double) {
497        int i = Doubles.indexOf(array, (Double) target, start, end);
498        if (i >= 0) {
499          return i - start;
500        }
501      }
502      return -1;
503    }
504
505    @Override
506    public int lastIndexOf(Object target) {
507      // Overridden to prevent a ton of boxing
508      if (target instanceof Double) {
509        int i = Doubles.lastIndexOf(array, (Double) target, start, end);
510        if (i >= 0) {
511          return i - start;
512        }
513      }
514      return -1;
515    }
516
517    @Override
518    public Double set(int index, Double element) {
519      checkElementIndex(index, size());
520      double oldValue = array[start + index];
521      // checkNotNull for GWT (do not optimize)
522      array[start + index] = checkNotNull(element);
523      return oldValue;
524    }
525
526    @Override
527    public List<Double> subList(int fromIndex, int toIndex) {
528      int size = size();
529      checkPositionIndexes(fromIndex, toIndex, size);
530      if (fromIndex == toIndex) {
531        return Collections.emptyList();
532      }
533      return new DoubleArrayAsList(array, start + fromIndex, start + toIndex);
534    }
535
536    @Override
537    public boolean equals(@Nullable Object object) {
538      if (object == this) {
539        return true;
540      }
541      if (object instanceof DoubleArrayAsList) {
542        DoubleArrayAsList that = (DoubleArrayAsList) object;
543        int size = size();
544        if (that.size() != size) {
545          return false;
546        }
547        for (int i = 0; i < size; i++) {
548          if (array[start + i] != that.array[that.start + i]) {
549            return false;
550          }
551        }
552        return true;
553      }
554      return super.equals(object);
555    }
556
557    @Override
558    public int hashCode() {
559      int result = 1;
560      for (int i = start; i < end; i++) {
561        result = 31 * result + Doubles.hashCode(array[i]);
562      }
563      return result;
564    }
565
566    @Override
567    public String toString() {
568      StringBuilder builder = new StringBuilder(size() * 12);
569      builder.append('[').append(array[start]);
570      for (int i = start + 1; i < end; i++) {
571        builder.append(", ").append(array[i]);
572      }
573      return builder.append(']').toString();
574    }
575
576    double[] toDoubleArray() {
577      return Arrays.copyOfRange(array, start, end);
578    }
579
580    private static final long serialVersionUID = 0;
581  }
582
583  /**
584   * This is adapted from the regex suggested by {@link Double#valueOf(String)} for prevalidating
585   * inputs. All valid inputs must pass this regex, but it's semantically fine if not all inputs
586   * that pass this regex are valid -- only a performance hit is incurred, not a semantics bug.
587   */
588  @GwtIncompatible // regular expressions
589  static final Pattern FLOATING_POINT_PATTERN = fpPattern();
590
591  @GwtIncompatible // regular expressions
592  private static Pattern fpPattern() {
593    String decimal = "(?:\\d++(?:\\.\\d*+)?|\\.\\d++)";
594    String completeDec = decimal + "(?:[eE][+-]?\\d++)?[fFdD]?";
595    String hex = "(?:\\p{XDigit}++(?:\\.\\p{XDigit}*+)?|\\.\\p{XDigit}++)";
596    String completeHex = "0[xX]" + hex + "[pP][+-]?\\d++[fFdD]?";
597    String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")";
598    return Pattern.compile(fpPattern);
599  }
600
601  /**
602   * Parses the specified string as a double-precision floating point value. The ASCII character
603   * {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign.
604   *
605   * <p>Unlike {@link Double#parseDouble(String)}, this method returns {@code null} instead of
606   * throwing an exception if parsing fails. Valid inputs are exactly those accepted by
607   * {@link Double#valueOf(String)}, except that leading and trailing whitespace is not permitted.
608   *
609   * <p>This implementation is likely to be faster than {@code
610   * Double.parseDouble} if many failures are expected.
611   *
612   * @param string the string representation of a {@code double} value
613   * @return the floating point value represented by {@code string}, or {@code null} if
614   *     {@code string} has a length of zero or cannot be parsed as a {@code double} value
615   * @since 14.0
616   */
617  @Beta
618  @Nullable
619  @CheckForNull
620  @GwtIncompatible // regular expressions
621  public static Double tryParse(String string) {
622    if (FLOATING_POINT_PATTERN.matcher(string).matches()) {
623      // TODO(lowasser): could be potentially optimized, but only with
624      // extensive testing
625      try {
626        return Double.parseDouble(string);
627      } catch (NumberFormatException e) {
628        // Double.parseDouble has changed specs several times, so fall through
629        // gracefully
630      }
631    }
632    return null;
633  }
634}