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