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 values from each provided array combined into a single array. For example,
243   * {@code concat(new double[] {a, b}, new double[] {}, new double[] {c}} returns the array
244   * {@code {a, b, c}}.
245   *
246   * @param arrays zero or more {@code double} arrays
247   * @return a single array containing all the values from the source arrays, in order
248   */
249  public static double[] concat(double[]... arrays) {
250    int length = 0;
251    for (double[] array : arrays) {
252      length += array.length;
253    }
254    double[] result = new double[length];
255    int pos = 0;
256    for (double[] array : arrays) {
257      System.arraycopy(array, 0, result, pos, array.length);
258      pos += array.length;
259    }
260    return result;
261  }
262
263  private static final class DoubleConverter extends Converter<String, Double>
264      implements Serializable {
265    static final DoubleConverter INSTANCE = new DoubleConverter();
266
267    @Override
268    protected Double doForward(String value) {
269      return Double.valueOf(value);
270    }
271
272    @Override
273    protected String doBackward(Double value) {
274      return value.toString();
275    }
276
277    @Override
278    public String toString() {
279      return "Doubles.stringConverter()";
280    }
281
282    private Object readResolve() {
283      return INSTANCE;
284    }
285
286    private static final long serialVersionUID = 1;
287  }
288
289  /**
290   * Returns a serializable converter object that converts between strings and doubles using
291   * {@link Double#valueOf} and {@link Double#toString()}.
292   *
293   * @since 16.0
294   */
295  @Beta
296  public static Converter<String, Double> stringConverter() {
297    return DoubleConverter.INSTANCE;
298  }
299
300  /**
301   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
302   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
303   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
304   * returned, containing the values of {@code array}, and zeroes in the remaining places.
305   *
306   * @param array the source array
307   * @param minLength the minimum length the returned array must guarantee
308   * @param padding an extra amount to "grow" the array by if growth is necessary
309   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
310   * @return an array containing the values of {@code array}, with guaranteed minimum length
311   *     {@code minLength}
312   */
313  public static double[] ensureCapacity(double[] array, int minLength, int padding) {
314    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
315    checkArgument(padding >= 0, "Invalid padding: %s", padding);
316    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
317  }
318
319  /**
320   * Returns a string containing the supplied {@code double} values, converted to strings as
321   * specified by {@link Double#toString(double)}, and separated by {@code separator}. For example,
322   * {@code join("-", 1.0, 2.0, 3.0)} returns the string {@code "1.0-2.0-3.0"}.
323   *
324   * <p>Note that {@link Double#toString(double)} formats {@code double} differently in GWT
325   * sometimes. In the previous example, it returns the string {@code "1-2-3"}.
326   *
327   * @param separator the text that should appear between consecutive values in the resulting string
328   *     (but not at the start or end)
329   * @param array an array of {@code double} values, possibly empty
330   */
331  public static String join(String separator, double... array) {
332    checkNotNull(separator);
333    if (array.length == 0) {
334      return "";
335    }
336
337    // For pre-sizing a builder, just get the right order of magnitude
338    StringBuilder builder = new StringBuilder(array.length * 12);
339    builder.append(array[0]);
340    for (int i = 1; i < array.length; i++) {
341      builder.append(separator).append(array[i]);
342    }
343    return builder.toString();
344  }
345
346  /**
347   * Returns a comparator that compares two {@code double} arrays <a
348   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
349   * compares, using {@link #compare(double, double)}), the first pair of values that follow any
350   * common prefix, or when one array is a prefix of the other, treats the shorter array as the
351   * lesser. For example, {@code [] < [1.0] < [1.0, 2.0] < [2.0]}.
352   *
353   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
354   * support only identity equality), but it is consistent with
355   * {@link Arrays#equals(double[], double[])}.
356   *
357   * @since 2.0
358   */
359  public static Comparator<double[]> lexicographicalComparator() {
360    return LexicographicalComparator.INSTANCE;
361  }
362
363  private enum LexicographicalComparator implements Comparator<double[]> {
364    INSTANCE;
365
366    @Override
367    public int compare(double[] left, double[] right) {
368      int minLength = Math.min(left.length, right.length);
369      for (int i = 0; i < minLength; i++) {
370        int result = Double.compare(left[i], right[i]);
371        if (result != 0) {
372          return result;
373        }
374      }
375      return left.length - right.length;
376    }
377
378    @Override
379    public String toString() {
380      return "Doubles.lexicographicalComparator()";
381    }
382  }
383
384  /**
385   * Returns an array containing each value of {@code collection}, converted to a {@code double}
386   * value in the manner of {@link Number#doubleValue}.
387   *
388   * <p>Elements are copied from the argument collection as if by {@code
389   * collection.toArray()}. Calling this method is as thread-safe as calling that method.
390   *
391   * @param collection a collection of {@code Number} instances
392   * @return an array containing the same values as {@code collection}, in the same order, converted
393   *     to primitives
394   * @throws NullPointerException if {@code collection} or any of its elements is null
395   * @since 1.0 (parameter was {@code Collection<Double>} before 12.0)
396   */
397  public static double[] toArray(Collection<? extends Number> collection) {
398    if (collection instanceof DoubleArrayAsList) {
399      return ((DoubleArrayAsList) collection).toDoubleArray();
400    }
401
402    Object[] boxedArray = collection.toArray();
403    int len = boxedArray.length;
404    double[] array = new double[len];
405    for (int i = 0; i < len; i++) {
406      // checkNotNull for GWT (do not optimize)
407      array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue();
408    }
409    return array;
410  }
411
412  /**
413   * Returns a fixed-size list backed by the specified array, similar to
414   * {@link Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any
415   * attempt to set a value to {@code null} will result in a {@link NullPointerException}.
416   *
417   * <p>The returned list maintains the values, but not the identities, of {@code Double} objects
418   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
419   * the returned list is unspecified.
420   *
421   * <p>The returned list may have unexpected behavior if it contains {@code
422   * NaN}, or if {@code NaN} is used as a parameter to any of its methods.
423   *
424   * @param backingArray the array to back the list
425   * @return a list view of the array
426   */
427  public static List<Double> asList(double... backingArray) {
428    if (backingArray.length == 0) {
429      return Collections.emptyList();
430    }
431    return new DoubleArrayAsList(backingArray);
432  }
433
434  @GwtCompatible
435  private static class DoubleArrayAsList extends AbstractList<Double>
436      implements RandomAccess, Serializable {
437    final double[] array;
438    final int start;
439    final int end;
440
441    DoubleArrayAsList(double[] array) {
442      this(array, 0, array.length);
443    }
444
445    DoubleArrayAsList(double[] array, int start, int end) {
446      this.array = array;
447      this.start = start;
448      this.end = end;
449    }
450
451    @Override
452    public int size() {
453      return end - start;
454    }
455
456    @Override
457    public boolean isEmpty() {
458      return false;
459    }
460
461    @Override
462    public Double get(int index) {
463      checkElementIndex(index, size());
464      return array[start + index];
465    }
466
467    @Override
468    public boolean contains(Object target) {
469      // Overridden to prevent a ton of boxing
470      return (target instanceof Double)
471          && Doubles.indexOf(array, (Double) target, start, end) != -1;
472    }
473
474    @Override
475    public int indexOf(Object target) {
476      // Overridden to prevent a ton of boxing
477      if (target instanceof Double) {
478        int i = Doubles.indexOf(array, (Double) target, start, end);
479        if (i >= 0) {
480          return i - start;
481        }
482      }
483      return -1;
484    }
485
486    @Override
487    public int lastIndexOf(Object target) {
488      // Overridden to prevent a ton of boxing
489      if (target instanceof Double) {
490        int i = Doubles.lastIndexOf(array, (Double) target, start, end);
491        if (i >= 0) {
492          return i - start;
493        }
494      }
495      return -1;
496    }
497
498    @Override
499    public Double set(int index, Double element) {
500      checkElementIndex(index, size());
501      double oldValue = array[start + index];
502      // checkNotNull for GWT (do not optimize)
503      array[start + index] = checkNotNull(element);
504      return oldValue;
505    }
506
507    @Override
508    public List<Double> subList(int fromIndex, int toIndex) {
509      int size = size();
510      checkPositionIndexes(fromIndex, toIndex, size);
511      if (fromIndex == toIndex) {
512        return Collections.emptyList();
513      }
514      return new DoubleArrayAsList(array, start + fromIndex, start + toIndex);
515    }
516
517    @Override
518    public boolean equals(@Nullable Object object) {
519      if (object == this) {
520        return true;
521      }
522      if (object instanceof DoubleArrayAsList) {
523        DoubleArrayAsList that = (DoubleArrayAsList) object;
524        int size = size();
525        if (that.size() != size) {
526          return false;
527        }
528        for (int i = 0; i < size; i++) {
529          if (array[start + i] != that.array[that.start + i]) {
530            return false;
531          }
532        }
533        return true;
534      }
535      return super.equals(object);
536    }
537
538    @Override
539    public int hashCode() {
540      int result = 1;
541      for (int i = start; i < end; i++) {
542        result = 31 * result + Doubles.hashCode(array[i]);
543      }
544      return result;
545    }
546
547    @Override
548    public String toString() {
549      StringBuilder builder = new StringBuilder(size() * 12);
550      builder.append('[').append(array[start]);
551      for (int i = start + 1; i < end; i++) {
552        builder.append(", ").append(array[i]);
553      }
554      return builder.append(']').toString();
555    }
556
557    double[] toDoubleArray() {
558      // Arrays.copyOfRange() is not available under GWT
559      int size = size();
560      double[] result = new double[size];
561      System.arraycopy(array, start, result, 0, size);
562      return result;
563    }
564
565    private static final long serialVersionUID = 0;
566  }
567
568  /**
569   * This is adapted from the regex suggested by {@link Double#valueOf(String)} for prevalidating
570   * inputs. All valid inputs must pass this regex, but it's semantically fine if not all inputs
571   * that pass this regex are valid -- only a performance hit is incurred, not a semantics bug.
572   */
573  @GwtIncompatible // regular expressions
574  static final Pattern FLOATING_POINT_PATTERN = fpPattern();
575
576  @GwtIncompatible // regular expressions
577  private static Pattern fpPattern() {
578    String decimal = "(?:\\d++(?:\\.\\d*+)?|\\.\\d++)";
579    String completeDec = decimal + "(?:[eE][+-]?\\d++)?[fFdD]?";
580    String hex = "(?:\\p{XDigit}++(?:\\.\\p{XDigit}*+)?|\\.\\p{XDigit}++)";
581    String completeHex = "0[xX]" + hex + "[pP][+-]?\\d++[fFdD]?";
582    String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")";
583    return Pattern.compile(fpPattern);
584  }
585
586  /**
587   * Parses the specified string as a double-precision floating point value. The ASCII character
588   * {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign.
589   *
590   * <p>Unlike {@link Double#parseDouble(String)}, this method returns {@code null} instead of
591   * throwing an exception if parsing fails. Valid inputs are exactly those accepted by
592   * {@link Double#valueOf(String)}, except that leading and trailing whitespace is not permitted.
593   *
594   * <p>This implementation is likely to be faster than {@code
595   * Double.parseDouble} if many failures are expected.
596   *
597   * @param string the string representation of a {@code double} value
598   * @return the floating point value represented by {@code string}, or {@code null} if
599   *     {@code string} has a length of zero or cannot be parsed as a {@code double} value
600   * @since 14.0
601   */
602  @Beta
603  @Nullable
604  @CheckForNull
605  @GwtIncompatible // regular expressions
606  public static Double tryParse(String string) {
607    if (FLOATING_POINT_PATTERN.matcher(string).matches()) {
608      // TODO(lowasser): could be potentially optimized, but only with
609      // extensive testing
610      try {
611        return Double.parseDouble(string);
612      } catch (NumberFormatException e) {
613        // Double.parseDouble has changed specs several times, so fall through
614        // gracefully
615      }
616    }
617    return null;
618  }
619}