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