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