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