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.CheckForNull;
042import javax.annotation.CheckReturnValue;
043import javax.annotation.Nullable;
044
045/**
046 * Static utility methods pertaining to {@code double} primitives, that are not
047 * already found in either {@link Double} or {@link Arrays}.
048 *
049 * <p>See the Guava User Guide article on <a href=
050 * "https://github.com/google/guava/wiki/PrimitivesExplained">
051 * primitive utilities</a>.
052 *
053 * @author Kevin Bourrillion
054 * @since 1.0
055 */
056@CheckReturnValue
057@GwtCompatible(emulated = true)
058public final class Doubles {
059  private Doubles() {}
060
061  /**
062   * The number of bytes required to represent a primitive {@code double}
063   * value.
064   *
065   * @since 10.0
066   */
067  public static final int BYTES = Double.SIZE / Byte.SIZE;
068
069  /**
070   * Returns a hash code for {@code value}; equal to the result of invoking
071   * {@code ((Double) value).hashCode()}.
072   *
073   * @param value a primitive {@code double} value
074   * @return a hash code for the value
075   */
076  public static int hashCode(double value) {
077    return ((Double) value).hashCode();
078    // TODO(kevinb): do it this way when we can (GWT problem):
079    // long bits = Double.doubleToLongBits(value);
080    // return (int) (bits ^ (bits >>> 32));
081  }
082
083  /**
084   * Compares the two specified {@code double} values. The sign of the value
085   * returned is the same as that of <code>((Double) a).{@linkplain
086   * Double#compareTo compareTo}(b)</code>. As with that method, {@code NaN} is
087   * treated as greater than all other values, and {@code 0.0 > -0.0}.
088   *
089   * <p><b>Note:</b> this method simply delegates to the JDK method {@link
090   * Double#compare}. It is provided for consistency with the other primitive
091   * types, whose compare methods were not added to the JDK until JDK 7.
092   *
093   * @param a the first {@code double} to compare
094   * @param b the second {@code double} to compare
095   * @return a negative value if {@code a} is less than {@code b}; a positive
096   *     value if {@code a} is greater than {@code b}; or zero if they are equal
097   */
098  public static int compare(double a, double b) {
099    return Double.compare(a, b);
100  }
101
102  /**
103   * Returns {@code true} if {@code value} represents a real number. This is
104   * equivalent to, but not necessarily implemented as,
105   * {@code !(Double.isInfinite(value) || Double.isNaN(value))}.
106   *
107   * @since 10.0
108   */
109  public static boolean isFinite(double value) {
110    return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY;
111  }
112
113  /**
114   * Returns {@code true} if {@code target} is present as an element anywhere in
115   * {@code array}. Note that this always returns {@code false} when {@code
116   * target} is {@code NaN}.
117   *
118   * @param array an array of {@code double} values, possibly empty
119   * @param target a primitive {@code double} value
120   * @return {@code true} if {@code array[i] == target} for some value of {@code
121   *     i}
122   */
123  public static boolean contains(double[] array, double target) {
124    for (double value : array) {
125      if (value == target) {
126        return true;
127      }
128    }
129    return false;
130  }
131
132  /**
133   * Returns the index of the first appearance of the value {@code target} in
134   * {@code array}. Note that this always returns {@code -1} when {@code target}
135   * is {@code NaN}.
136   *
137   * @param array an array of {@code double} values, possibly empty
138   * @param target a primitive {@code double} value
139   * @return the least index {@code i} for which {@code array[i] == target}, or
140   *     {@code -1} if no such index exists.
141   */
142  public static int indexOf(double[] array, double target) {
143    return indexOf(array, target, 0, array.length);
144  }
145
146  // TODO(kevinb): consider making this public
147  private static int indexOf(double[] array, double target, int start, int end) {
148    for (int i = start; i < end; i++) {
149      if (array[i] == target) {
150        return i;
151      }
152    }
153    return -1;
154  }
155
156  /**
157   * Returns the start position of the first occurrence of the specified {@code
158   * target} within {@code array}, or {@code -1} if there is no such occurrence.
159   *
160   * <p>More formally, returns the lowest index {@code i} such that {@code
161   * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
162   * the same elements as {@code target}.
163   *
164   * <p>Note that this always returns {@code -1} when {@code target} contains
165   * {@code NaN}.
166   *
167   * @param array the array to search for the sequence {@code target}
168   * @param target the array to search for as a sub-sequence of {@code array}
169   */
170  public static int indexOf(double[] array, double[] target) {
171    checkNotNull(array, "array");
172    checkNotNull(target, "target");
173    if (target.length == 0) {
174      return 0;
175    }
176
177    outer:
178    for (int i = 0; i < array.length - target.length + 1; i++) {
179      for (int j = 0; j < target.length; j++) {
180        if (array[i + j] != target[j]) {
181          continue outer;
182        }
183      }
184      return i;
185    }
186    return -1;
187  }
188
189  /**
190   * Returns the index of the last appearance of the value {@code target} in
191   * {@code array}. Note that this always returns {@code -1} when {@code target}
192   * is {@code NaN}.
193   *
194   * @param array an array of {@code double} values, possibly empty
195   * @param target a primitive {@code double} value
196   * @return the greatest index {@code i} for which {@code array[i] == target},
197   *     or {@code -1} if no such index exists.
198   */
199  public static int lastIndexOf(double[] array, double target) {
200    return lastIndexOf(array, target, 0, array.length);
201  }
202
203  // TODO(kevinb): consider making this public
204  private static int lastIndexOf(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 extends Converter<String, Double>
273      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
295    private static final long serialVersionUID = 1;
296  }
297
298  /**
299   * Returns a serializable converter object that converts between strings and
300   * doubles using {@link Double#valueOf} and {@link Double#toString()}.
301   *
302   * @since 16.0
303   */
304  @Beta
305  public static Converter<String, Double> stringConverter() {
306    return DoubleConverter.INSTANCE;
307  }
308
309  /**
310   * Returns an array containing the same values as {@code array}, but
311   * guaranteed to be of a specified minimum length. If {@code array} already
312   * has a length of at least {@code minLength}, it is returned directly.
313   * Otherwise, a new array of size {@code minLength + padding} is returned,
314   * containing the values of {@code array}, and zeroes in the remaining places.
315   *
316   * @param array the source array
317   * @param minLength the minimum length the returned array must guarantee
318   * @param padding an extra amount to "grow" the array by if growth is
319   *     necessary
320   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
321   *     negative
322   * @return an array containing the values of {@code array}, with guaranteed
323   *     minimum length {@code minLength}
324   */
325  public static double[] ensureCapacity(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 = Double.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
477    public int size() {
478      return end - start;
479    }
480
481    @Override
482    public boolean isEmpty() {
483      return false;
484    }
485
486    @Override
487    public Double get(int index) {
488      checkElementIndex(index, size());
489      return array[start + index];
490    }
491
492    @Override
493    public boolean contains(Object target) {
494      // Overridden to prevent a ton of boxing
495      return (target instanceof Double)
496          && Doubles.indexOf(array, (Double) target, start, end) != -1;
497    }
498
499    @Override
500    public int indexOf(Object target) {
501      // Overridden to prevent a ton of boxing
502      if (target instanceof Double) {
503        int i = Doubles.indexOf(array, (Double) target, start, end);
504        if (i >= 0) {
505          return i - start;
506        }
507      }
508      return -1;
509    }
510
511    @Override
512    public int lastIndexOf(Object target) {
513      // Overridden to prevent a ton of boxing
514      if (target instanceof Double) {
515        int i = Doubles.lastIndexOf(array, (Double) target, start, end);
516        if (i >= 0) {
517          return i - start;
518        }
519      }
520      return -1;
521    }
522
523    @Override
524    public Double set(int index, Double element) {
525      checkElementIndex(index, size());
526      double oldValue = array[start + index];
527      // checkNotNull for GWT (do not optimize)
528      array[start + index] = checkNotNull(element);
529      return oldValue;
530    }
531
532    @Override
533    public List<Double> subList(int fromIndex, int toIndex) {
534      int size = size();
535      checkPositionIndexes(fromIndex, toIndex, size);
536      if (fromIndex == toIndex) {
537        return Collections.emptyList();
538      }
539      return new DoubleArrayAsList(array, start + fromIndex, start + toIndex);
540    }
541
542    @Override
543    public boolean equals(@Nullable Object object) {
544      if (object == this) {
545        return true;
546      }
547      if (object instanceof DoubleArrayAsList) {
548        DoubleArrayAsList that = (DoubleArrayAsList) object;
549        int size = size();
550        if (that.size() != size) {
551          return false;
552        }
553        for (int i = 0; i < size; i++) {
554          if (array[start + i] != that.array[that.start + i]) {
555            return false;
556          }
557        }
558        return true;
559      }
560      return super.equals(object);
561    }
562
563    @Override
564    public int hashCode() {
565      int result = 1;
566      for (int i = start; i < end; i++) {
567        result = 31 * result + Doubles.hashCode(array[i]);
568      }
569      return result;
570    }
571
572    @Override
573    public String toString() {
574      StringBuilder builder = new StringBuilder(size() * 12);
575      builder.append('[').append(array[start]);
576      for (int i = start + 1; i < end; i++) {
577        builder.append(", ").append(array[i]);
578      }
579      return builder.append(']').toString();
580    }
581
582    double[] toDoubleArray() {
583      // Arrays.copyOfRange() is not available under GWT
584      int size = size();
585      double[] result = new double[size];
586      System.arraycopy(array, start, result, 0, size);
587      return result;
588    }
589
590    private static final long serialVersionUID = 0;
591  }
592
593  /**
594   * This is adapted from the regex suggested by {@link Double#valueOf(String)}
595   * for prevalidating inputs.  All valid inputs must pass this regex, but it's
596   * semantically fine if not all inputs that pass this regex are valid --
597   * only a performance hit is incurred, not a semantics bug.
598   */
599  @GwtIncompatible("regular expressions")
600  static final Pattern FLOATING_POINT_PATTERN = fpPattern();
601
602  @GwtIncompatible("regular expressions")
603  private static Pattern fpPattern() {
604    String decimal = "(?:\\d++(?:\\.\\d*+)?|\\.\\d++)";
605    String completeDec = decimal + "(?:[eE][+-]?\\d++)?[fFdD]?";
606    String hex = "(?:\\p{XDigit}++(?:\\.\\p{XDigit}*+)?|\\.\\p{XDigit}++)";
607    String completeHex = "0[xX]" + hex + "[pP][+-]?\\d++[fFdD]?";
608    String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")";
609    return Pattern.compile(fpPattern);
610  }
611
612  /**
613   * Parses the specified string as a double-precision floating point value.
614   * The ASCII character {@code '-'} (<code>'&#92;u002D'</code>) is recognized
615   * as the minus sign.
616   *
617   * <p>Unlike {@link Double#parseDouble(String)}, this method returns
618   * {@code null} instead of throwing an exception if parsing fails.
619   * Valid inputs are exactly those accepted by {@link Double#valueOf(String)},
620   * except that leading and trailing whitespace is not permitted.
621   *
622   * <p>This implementation is likely to be faster than {@code
623   * Double.parseDouble} if many failures are expected.
624   *
625   * @param string the string representation of a {@code double} value
626   * @return the floating point value represented by {@code string}, or
627   *     {@code null} if {@code string} has a length of zero or cannot be
628   *     parsed as a {@code double} value
629   * @since 14.0
630   */
631  @Beta
632  @Nullable
633  @CheckForNull
634  @GwtIncompatible("regular expressions")
635  public static Double tryParse(String string) {
636    if (FLOATING_POINT_PATTERN.matcher(string).matches()) {
637      // TODO(lowasser): could be potentially optimized, but only with
638      // extensive testing
639      try {
640        return Double.parseDouble(string);
641      } catch (NumberFormatException e) {
642        // Double.parseDouble has changed specs several times, so fall through
643        // gracefully
644      }
645    }
646    return null;
647  }
648}