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.GwtCompatible;
026import com.google.common.annotations.GwtIncompatible;
027import com.google.common.annotations.J2ktIncompatible;
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  public static float constrainToRange(float value, float min, float max) {
254    // avoid auto-boxing by not using Preconditions.checkArgument(); see Guava issue 3984
255    // Reject NaN by testing for the good case (min <= max) instead of the bad (min > max).
256    if (min <= max) {
257      return Math.min(Math.max(value, min), max);
258    }
259    throw new IllegalArgumentException(
260        lenientFormat("min (%s) must be less than or equal to max (%s)", min, max));
261  }
262
263  /**
264   * Returns the values from each provided array combined into a single array. For example, {@code
265   * concat(new float[] {a, b}, new float[] {}, new float[] {c}} returns the array {@code {a, b,
266   * c}}.
267   *
268   * @param arrays zero or more {@code float} arrays
269   * @return a single array containing all the values from the source arrays, in order
270   */
271  public static float[] concat(float[]... arrays) {
272    int length = 0;
273    for (float[] array : arrays) {
274      length += array.length;
275    }
276    float[] result = new float[length];
277    int pos = 0;
278    for (float[] array : arrays) {
279      System.arraycopy(array, 0, result, pos, array.length);
280      pos += array.length;
281    }
282    return result;
283  }
284
285  private static final class FloatConverter extends Converter<String, Float>
286      implements Serializable {
287    static final FloatConverter INSTANCE = new FloatConverter();
288
289    @Override
290    protected Float doForward(String value) {
291      return Float.valueOf(value);
292    }
293
294    @Override
295    protected String doBackward(Float value) {
296      return value.toString();
297    }
298
299    @Override
300    public String toString() {
301      return "Floats.stringConverter()";
302    }
303
304    private Object readResolve() {
305      return INSTANCE;
306    }
307
308    private static final long serialVersionUID = 1;
309  }
310
311  /**
312   * Returns a serializable converter object that converts between strings and floats using {@link
313   * Float#valueOf} and {@link Float#toString()}.
314   *
315   * @since 16.0
316   */
317  public static Converter<String, Float> stringConverter() {
318    return FloatConverter.INSTANCE;
319  }
320
321  /**
322   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
323   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
324   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
325   * returned, containing the values of {@code array}, and zeroes in the remaining places.
326   *
327   * @param array the source array
328   * @param minLength the minimum length the returned array must guarantee
329   * @param padding an extra amount to "grow" the array by if growth is necessary
330   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
331   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
332   *     minLength}
333   */
334  public static float[] ensureCapacity(float[] array, int minLength, int padding) {
335    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
336    checkArgument(padding >= 0, "Invalid padding: %s", padding);
337    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
338  }
339
340  /**
341   * Returns a string containing the supplied {@code float} values, converted to strings as
342   * specified by {@link Float#toString(float)}, and separated by {@code separator}. For example,
343   * {@code join("-", 1.0f, 2.0f, 3.0f)} returns the string {@code "1.0-2.0-3.0"}.
344   *
345   * <p>Note that {@link Float#toString(float)} formats {@code float} differently in GWT. In the
346   * previous example, it returns the string {@code "1-2-3"}.
347   *
348   * @param separator the text that should appear between consecutive values in the resulting string
349   *     (but not at the start or end)
350   * @param array an array of {@code float} values, possibly empty
351   */
352  public static String join(String separator, float... array) {
353    checkNotNull(separator);
354    if (array.length == 0) {
355      return "";
356    }
357
358    // For pre-sizing a builder, just get the right order of magnitude
359    StringBuilder builder = new StringBuilder(array.length * 12);
360    builder.append(array[0]);
361    for (int i = 1; i < array.length; i++) {
362      builder.append(separator).append(array[i]);
363    }
364    return builder.toString();
365  }
366
367  /**
368   * Returns a comparator that compares two {@code float} arrays <a
369   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
370   * compares, using {@link #compare(float, float)}), the first pair of values that follow any
371   * common prefix, or when one array is a prefix of the other, treats the shorter array as the
372   * lesser. For example, {@code [] < [1.0f] < [1.0f, 2.0f] < [2.0f]}.
373   *
374   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
375   * support only identity equality), but it is consistent with {@link Arrays#equals(float[],
376   * float[])}.
377   *
378   * @since 2.0
379   */
380  public static Comparator<float[]> lexicographicalComparator() {
381    return LexicographicalComparator.INSTANCE;
382  }
383
384  private enum LexicographicalComparator implements Comparator<float[]> {
385    INSTANCE;
386
387    @Override
388    public int compare(float[] left, float[] right) {
389      int minLength = Math.min(left.length, right.length);
390      for (int i = 0; i < minLength; i++) {
391        int result = Float.compare(left[i], right[i]);
392        if (result != 0) {
393          return result;
394        }
395      }
396      return left.length - right.length;
397    }
398
399    @Override
400    public String toString() {
401      return "Floats.lexicographicalComparator()";
402    }
403  }
404
405  /**
406   * Sorts the elements of {@code array} in descending order.
407   *
408   * <p>Note that this method uses the total order imposed by {@link Float#compare}, which treats
409   * all NaN values as equal and 0.0 as greater than -0.0.
410   *
411   * @since 23.1
412   */
413  public static void sortDescending(float[] array) {
414    checkNotNull(array);
415    sortDescending(array, 0, array.length);
416  }
417
418  /**
419   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
420   * exclusive in descending order.
421   *
422   * <p>Note that this method uses the total order imposed by {@link Float#compare}, which treats
423   * all NaN values as equal and 0.0 as greater than -0.0.
424   *
425   * @since 23.1
426   */
427  public static void sortDescending(float[] array, int fromIndex, int toIndex) {
428    checkNotNull(array);
429    checkPositionIndexes(fromIndex, toIndex, array.length);
430    Arrays.sort(array, fromIndex, toIndex);
431    reverse(array, fromIndex, toIndex);
432  }
433
434  /**
435   * Reverses the elements of {@code array}. This is equivalent to {@code
436   * Collections.reverse(Floats.asList(array))}, but is likely to be more efficient.
437   *
438   * @since 23.1
439   */
440  public static void reverse(float[] array) {
441    checkNotNull(array);
442    reverse(array, 0, array.length);
443  }
444
445  /**
446   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
447   * exclusive. This is equivalent to {@code
448   * Collections.reverse(Floats.asList(array).subList(fromIndex, toIndex))}, but is likely to be
449   * more efficient.
450   *
451   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
452   *     {@code toIndex > fromIndex}
453   * @since 23.1
454   */
455  public static void reverse(float[] array, int fromIndex, int toIndex) {
456    checkNotNull(array);
457    checkPositionIndexes(fromIndex, toIndex, array.length);
458    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
459      float tmp = array[i];
460      array[i] = array[j];
461      array[j] = tmp;
462    }
463  }
464
465  /**
466   * Performs a right rotation of {@code array} of "distance" places, so that the first element is
467   * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
468   * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Floats.asList(array),
469   * distance)}, but is considerably faster and avoids allocation and garbage collection.
470   *
471   * <p>The provided "distance" may be negative, which will rotate left.
472   *
473   * @since 32.0.0
474   */
475  public static void rotate(float[] array, int distance) {
476    rotate(array, distance, 0, array.length);
477  }
478
479  /**
480   * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
481   * toIndex} exclusive. This is equivalent to {@code
482   * Collections.rotate(Floats.asList(array).subList(fromIndex, toIndex), distance)}, but is
483   * considerably faster and avoids allocations and garbage collection.
484   *
485   * <p>The provided "distance" may be negative, which will rotate left.
486   *
487   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
488   *     {@code toIndex > fromIndex}
489   * @since 32.0.0
490   */
491  public static void rotate(float[] array, int distance, int fromIndex, int toIndex) {
492    // See Ints.rotate for more details about possible algorithms here.
493    checkNotNull(array);
494    checkPositionIndexes(fromIndex, toIndex, array.length);
495    if (array.length <= 1) {
496      return;
497    }
498
499    int length = toIndex - fromIndex;
500    // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
501    // places left to rotate.
502    int m = -distance % length;
503    m = (m < 0) ? m + length : m;
504    // The current index of what will become the first element of the rotated section.
505    int newFirstIndex = m + fromIndex;
506    if (newFirstIndex == fromIndex) {
507      return;
508    }
509
510    reverse(array, fromIndex, newFirstIndex);
511    reverse(array, newFirstIndex, toIndex);
512    reverse(array, fromIndex, toIndex);
513  }
514
515  /**
516   * Returns an array containing each value of {@code collection}, converted to a {@code float}
517   * value in the manner of {@link Number#floatValue}.
518   *
519   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
520   * Calling this method is as thread-safe as calling that method.
521   *
522   * @param collection a collection of {@code Number} instances
523   * @return an array containing the same values as {@code collection}, in the same order, converted
524   *     to primitives
525   * @throws NullPointerException if {@code collection} or any of its elements is null
526   * @since 1.0 (parameter was {@code Collection<Float>} before 12.0)
527   */
528  public static float[] toArray(Collection<? extends Number> collection) {
529    if (collection instanceof FloatArrayAsList) {
530      return ((FloatArrayAsList) collection).toFloatArray();
531    }
532
533    Object[] boxedArray = collection.toArray();
534    int len = boxedArray.length;
535    float[] array = new float[len];
536    for (int i = 0; i < len; i++) {
537      // checkNotNull for GWT (do not optimize)
538      array[i] = ((Number) checkNotNull(boxedArray[i])).floatValue();
539    }
540    return array;
541  }
542
543  /**
544   * Returns a fixed-size list backed by the specified array, similar to {@link
545   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
546   * set a value to {@code null} will result in a {@link NullPointerException}.
547   *
548   * <p>The returned list maintains the values, but not the identities, of {@code Float} objects
549   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
550   * the returned list is unspecified.
551   *
552   * <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN}
553   * is used as a parameter to any of its methods.
554   *
555   * <p>The returned list is serializable.
556   *
557   * @param backingArray the array to back the list
558   * @return a list view of the array
559   */
560  public static List<Float> asList(float... backingArray) {
561    if (backingArray.length == 0) {
562      return Collections.emptyList();
563    }
564    return new FloatArrayAsList(backingArray);
565  }
566
567  @GwtCompatible
568  private static class FloatArrayAsList extends AbstractList<Float>
569      implements RandomAccess, Serializable {
570    final float[] array;
571    final int start;
572    final int end;
573
574    FloatArrayAsList(float[] array) {
575      this(array, 0, array.length);
576    }
577
578    FloatArrayAsList(float[] array, int start, int end) {
579      this.array = array;
580      this.start = start;
581      this.end = end;
582    }
583
584    @Override
585    public int size() {
586      return end - start;
587    }
588
589    @Override
590    public boolean isEmpty() {
591      return false;
592    }
593
594    @Override
595    public Float get(int index) {
596      checkElementIndex(index, size());
597      return array[start + index];
598    }
599
600    @Override
601    public boolean contains(@CheckForNull Object target) {
602      // Overridden to prevent a ton of boxing
603      return (target instanceof Float) && Floats.indexOf(array, (Float) target, start, end) != -1;
604    }
605
606    @Override
607    public int indexOf(@CheckForNull Object target) {
608      // Overridden to prevent a ton of boxing
609      if (target instanceof Float) {
610        int i = Floats.indexOf(array, (Float) target, start, end);
611        if (i >= 0) {
612          return i - start;
613        }
614      }
615      return -1;
616    }
617
618    @Override
619    public int lastIndexOf(@CheckForNull Object target) {
620      // Overridden to prevent a ton of boxing
621      if (target instanceof Float) {
622        int i = Floats.lastIndexOf(array, (Float) target, start, end);
623        if (i >= 0) {
624          return i - start;
625        }
626      }
627      return -1;
628    }
629
630    @Override
631    public Float set(int index, Float element) {
632      checkElementIndex(index, size());
633      float oldValue = array[start + index];
634      // checkNotNull for GWT (do not optimize)
635      array[start + index] = checkNotNull(element);
636      return oldValue;
637    }
638
639    @Override
640    public List<Float> subList(int fromIndex, int toIndex) {
641      int size = size();
642      checkPositionIndexes(fromIndex, toIndex, size);
643      if (fromIndex == toIndex) {
644        return Collections.emptyList();
645      }
646      return new FloatArrayAsList(array, start + fromIndex, start + toIndex);
647    }
648
649    @Override
650    public boolean equals(@CheckForNull Object object) {
651      if (object == this) {
652        return true;
653      }
654      if (object instanceof FloatArrayAsList) {
655        FloatArrayAsList that = (FloatArrayAsList) object;
656        int size = size();
657        if (that.size() != size) {
658          return false;
659        }
660        for (int i = 0; i < size; i++) {
661          if (array[start + i] != that.array[that.start + i]) {
662            return false;
663          }
664        }
665        return true;
666      }
667      return super.equals(object);
668    }
669
670    @Override
671    public int hashCode() {
672      int result = 1;
673      for (int i = start; i < end; i++) {
674        result = 31 * result + Floats.hashCode(array[i]);
675      }
676      return result;
677    }
678
679    @Override
680    public String toString() {
681      StringBuilder builder = new StringBuilder(size() * 12);
682      builder.append('[').append(array[start]);
683      for (int i = start + 1; i < end; i++) {
684        builder.append(", ").append(array[i]);
685      }
686      return builder.append(']').toString();
687    }
688
689    float[] toFloatArray() {
690      return Arrays.copyOfRange(array, start, end);
691    }
692
693    private static final long serialVersionUID = 0;
694  }
695
696  /**
697   * Parses the specified string as a single-precision floating point value. The ASCII character
698   * {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign.
699   *
700   * <p>Unlike {@link Float#parseFloat(String)}, this method returns {@code null} instead of
701   * throwing an exception if parsing fails. Valid inputs are exactly those accepted by {@link
702   * Float#valueOf(String)}, except that leading and trailing whitespace is not permitted.
703   *
704   * <p>This implementation is likely to be faster than {@code Float.parseFloat} if many failures
705   * are expected.
706   *
707   * @param string the string representation of a {@code float} value
708   * @return the floating point value represented by {@code string}, or {@code null} if {@code
709   *     string} has a length of zero or cannot be parsed as a {@code float} value
710   * @throws NullPointerException if {@code string} is {@code null}
711   * @since 14.0
712   */
713  @J2ktIncompatible
714  @GwtIncompatible // regular expressions
715  @CheckForNull
716  public static Float tryParse(String string) {
717    if (Doubles.FLOATING_POINT_PATTERN.matcher(string).matches()) {
718      // TODO(lowasser): could be potentially optimized, but only with
719      // extensive testing
720      try {
721        return Float.parseFloat(string);
722      } catch (NumberFormatException e) {
723        // Float.parseFloat has changed specs several times, so fall through
724        // gracefully
725      }
726    }
727    return null;
728  }
729}