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