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