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