001 /* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017 package com.google.common.primitives; 018 019 import static com.google.common.base.Preconditions.checkArgument; 020 import static com.google.common.base.Preconditions.checkElementIndex; 021 import static com.google.common.base.Preconditions.checkNotNull; 022 import static com.google.common.base.Preconditions.checkPositionIndexes; 023 import static java.lang.Double.NEGATIVE_INFINITY; 024 import static java.lang.Double.POSITIVE_INFINITY; 025 026 import com.google.common.annotations.GwtCompatible; 027 028 import java.io.Serializable; 029 import java.util.AbstractList; 030 import java.util.Arrays; 031 import java.util.Collection; 032 import java.util.Collections; 033 import java.util.Comparator; 034 import java.util.List; 035 import java.util.RandomAccess; 036 037 /** 038 * Static utility methods pertaining to {@code double} primitives, that are not 039 * already found in either {@link Double} or {@link Arrays}. 040 * 041 * <p>See the Guava User Guide article on <a href= 042 * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> 043 * primitive utilities</a>. 044 * 045 * @author Kevin Bourrillion 046 * @since 1.0 047 */ 048 @GwtCompatible 049 public final class Doubles { 050 private Doubles() {} 051 052 /** 053 * The number of bytes required to represent a primitive {@code double} 054 * value. 055 * 056 * @since 10.0 057 */ 058 public static final int BYTES = Double.SIZE / Byte.SIZE; 059 060 /** 061 * Returns a hash code for {@code value}; equal to the result of invoking 062 * {@code ((Double) value).hashCode()}. 063 * 064 * @param value a primitive {@code double} value 065 * @return a hash code for the value 066 */ 067 public static int hashCode(double value) { 068 return ((Double) value).hashCode(); 069 // TODO(kevinb): do it this way when we can (GWT problem): 070 // long bits = Double.doubleToLongBits(value); 071 // return (int)(bits ^ (bits >>> 32)); 072 } 073 074 /** 075 * Compares the two specified {@code double} values. The sign of the value 076 * returned is the same as that of <code>((Double) a).{@linkplain 077 * Double#compareTo compareTo}(b)</code>. As with that method, {@code NaN} is 078 * treated as greater than all other values, and {@code 0.0 > -0.0}. 079 * 080 * @param a the first {@code double} to compare 081 * @param b the second {@code double} to compare 082 * @return a negative value if {@code a} is less than {@code b}; a positive 083 * value if {@code a} is greater than {@code b}; or zero if they are equal 084 */ 085 public static int compare(double a, double b) { 086 return Double.compare(a, b); 087 } 088 089 /** 090 * Returns {@code true} if {@code value} represents a real number. This is 091 * equivalent to, but not necessarily implemented as, 092 * {@code !(Double.isInfinite(value) || Double.isNaN(value))}. 093 * 094 * @since 10.0 095 */ 096 public static boolean isFinite(double value) { 097 return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY; 098 } 099 100 /** 101 * Returns {@code true} if {@code target} is present as an element anywhere in 102 * {@code array}. Note that this always returns {@code false} when {@code 103 * target} is {@code NaN}. 104 * 105 * @param array an array of {@code double} values, possibly empty 106 * @param target a primitive {@code double} value 107 * @return {@code true} if {@code array[i] == target} for some value of {@code 108 * i} 109 */ 110 public static boolean contains(double[] array, double target) { 111 for (double value : array) { 112 if (value == target) { 113 return true; 114 } 115 } 116 return false; 117 } 118 119 /** 120 * Returns the index of the first appearance of the value {@code target} in 121 * {@code array}. Note that this always returns {@code -1} when {@code target} 122 * is {@code NaN}. 123 * 124 * @param array an array of {@code double} values, possibly empty 125 * @param target a primitive {@code double} value 126 * @return the least index {@code i} for which {@code array[i] == target}, or 127 * {@code -1} if no such index exists. 128 */ 129 public static int indexOf(double[] array, double target) { 130 return indexOf(array, target, 0, array.length); 131 } 132 133 // TODO(kevinb): consider making this public 134 private static int indexOf( 135 double[] array, double 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 146 * target} within {@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 149 * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly 150 * the same elements as {@code target}. 151 * 152 * <p>Note that this always returns {@code -1} when {@code target} contains 153 * {@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(double[] array, double[] 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 179 * {@code array}. Note that this always returns {@code -1} when {@code target} 180 * 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}, 185 * or {@code -1} if no 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( 193 double[] array, double target, int start, int end) { 194 for (int i = end - 1; i >= start; i--) { 195 if (array[i] == target) { 196 return i; 197 } 198 } 199 return -1; 200 } 201 202 /** 203 * Returns the least value present in {@code array}, using the same rules of 204 * comparison as {@link Math#min(double, double)}. 205 * 206 * @param array a <i>nonempty</i> array of {@code double} values 207 * @return the value present in {@code array} that is less than or equal to 208 * every other value in the array 209 * @throws IllegalArgumentException if {@code array} is empty 210 */ 211 public static double min(double... array) { 212 checkArgument(array.length > 0); 213 double 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 222 * of comparison as {@link Math#max(double, double)}. 223 * 224 * @param array a <i>nonempty</i> array of {@code double} values 225 * @return the value present in {@code array} that is greater than or equal to 226 * every other value in the array 227 * @throws IllegalArgumentException if {@code array} is empty 228 */ 229 public static double max(double... array) { 230 checkArgument(array.length > 0); 231 double 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 values from each provided array combined into a single array. 240 * For example, {@code concat(new double[] {a, b}, new double[] {}, new 241 * double[] {c}} returns the array {@code {a, b, c}}. 242 * 243 * @param arrays zero or more {@code double} arrays 244 * @return a single array containing all the values from the source arrays, in 245 * order 246 */ 247 public static double[] concat(double[]... arrays) { 248 int length = 0; 249 for (double[] array : arrays) { 250 length += array.length; 251 } 252 double[] result = new double[length]; 253 int pos = 0; 254 for (double[] array : arrays) { 255 System.arraycopy(array, 0, result, pos, array.length); 256 pos += array.length; 257 } 258 return result; 259 } 260 261 /** 262 * Returns an array containing the same values as {@code array}, but 263 * guaranteed to be of a specified minimum length. If {@code array} already 264 * has a length of at least {@code minLength}, it is returned directly. 265 * Otherwise, a new array of size {@code minLength + padding} is returned, 266 * containing the values of {@code array}, and zeroes in the remaining places. 267 * 268 * @param array the source array 269 * @param minLength the minimum length the returned array must guarantee 270 * @param padding an extra amount to "grow" the array by if growth is 271 * necessary 272 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is 273 * negative 274 * @return an array containing the values of {@code array}, with guaranteed 275 * minimum length {@code minLength} 276 */ 277 public static double[] ensureCapacity( 278 double[] array, int minLength, int padding) { 279 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 280 checkArgument(padding >= 0, "Invalid padding: %s", padding); 281 return (array.length < minLength) 282 ? copyOf(array, minLength + padding) 283 : array; 284 } 285 286 // Arrays.copyOf() requires Java 6 287 private static double[] copyOf(double[] original, int length) { 288 double[] copy = new double[length]; 289 System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); 290 return copy; 291 } 292 293 /** 294 * Returns a string containing the supplied {@code double} values, converted 295 * to strings as specified by {@link Double#toString(double)}, and separated 296 * by {@code separator}. For example, {@code join("-", 1.0, 2.0, 3.0)} returns 297 * the string {@code "1.0-2.0-3.0"}. 298 * 299 * <p>Note that {@link Double#toString(double)} formats {@code double} 300 * differently in GWT sometimes. In the previous example, it returns the string 301 * {@code "1-2-3"}. 302 * 303 * @param separator the text that should appear between consecutive values in 304 * the resulting string (but not at the start or end) 305 * @param array an array of {@code double} values, possibly empty 306 */ 307 public static String join(String separator, double... array) { 308 checkNotNull(separator); 309 if (array.length == 0) { 310 return ""; 311 } 312 313 // For pre-sizing a builder, just get the right order of magnitude 314 StringBuilder builder = new StringBuilder(array.length * 12); 315 builder.append(array[0]); 316 for (int i = 1; i < array.length; i++) { 317 builder.append(separator).append(array[i]); 318 } 319 return builder.toString(); 320 } 321 322 /** 323 * Returns a comparator that compares two {@code double} arrays 324 * lexicographically. That is, it compares, using {@link 325 * #compare(double, double)}), the first pair of values that follow any 326 * common prefix, or when one array is a prefix of the other, treats the 327 * shorter array as the lesser. For example, 328 * {@code [] < [1.0] < [1.0, 2.0] < [2.0]}. 329 * 330 * <p>The returned comparator is inconsistent with {@link 331 * Object#equals(Object)} (since arrays support only identity equality), but 332 * it is consistent with {@link Arrays#equals(double[], double[])}. 333 * 334 * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> 335 * Lexicographical order article at Wikipedia</a> 336 * @since 2.0 337 */ 338 public static Comparator<double[]> lexicographicalComparator() { 339 return LexicographicalComparator.INSTANCE; 340 } 341 342 private enum LexicographicalComparator implements Comparator<double[]> { 343 INSTANCE; 344 345 @Override 346 public int compare(double[] left, double[] right) { 347 int minLength = Math.min(left.length, right.length); 348 for (int i = 0; i < minLength; i++) { 349 int result = Doubles.compare(left[i], right[i]); 350 if (result != 0) { 351 return result; 352 } 353 } 354 return left.length - right.length; 355 } 356 } 357 358 /** 359 * Returns an array containing each value of {@code collection}, converted to 360 * a {@code double} value in the manner of {@link Number#doubleValue}. 361 * 362 * <p>Elements are copied from the argument collection as if by {@code 363 * collection.toArray()}. Calling this method is as thread-safe as calling 364 * that method. 365 * 366 * @param collection a collection of {@code Number} instances 367 * @return an array containing the same values as {@code collection}, in the 368 * same order, converted to primitives 369 * @throws NullPointerException if {@code collection} or any of its elements 370 * is null 371 * @since 1.0 (parameter was {@code Collection<Double>} before 12.0) 372 */ 373 public static double[] toArray(Collection<? extends Number> collection) { 374 if (collection instanceof DoubleArrayAsList) { 375 return ((DoubleArrayAsList) collection).toDoubleArray(); 376 } 377 378 Object[] boxedArray = collection.toArray(); 379 int len = boxedArray.length; 380 double[] array = new double[len]; 381 for (int i = 0; i < len; i++) { 382 // checkNotNull for GWT (do not optimize) 383 array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue(); 384 } 385 return array; 386 } 387 388 /** 389 * Returns a fixed-size list backed by the specified array, similar to {@link 390 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, 391 * but any attempt to set a value to {@code null} will result in a {@link 392 * NullPointerException}. 393 * 394 * <p>The returned list maintains the values, but not the identities, of 395 * {@code Double} objects written to or read from it. For example, whether 396 * {@code list.get(0) == list.get(0)} is true for the returned list is 397 * unspecified. 398 * 399 * <p>The returned list may have unexpected behavior if it contains {@code 400 * NaN}, or if {@code NaN} is used as a parameter to any of its methods. 401 * 402 * @param backingArray the array to back the list 403 * @return a list view of the array 404 */ 405 public static List<Double> asList(double... backingArray) { 406 if (backingArray.length == 0) { 407 return Collections.emptyList(); 408 } 409 return new DoubleArrayAsList(backingArray); 410 } 411 412 @GwtCompatible 413 private static class DoubleArrayAsList extends AbstractList<Double> 414 implements RandomAccess, Serializable { 415 final double[] array; 416 final int start; 417 final int end; 418 419 DoubleArrayAsList(double[] array) { 420 this(array, 0, array.length); 421 } 422 423 DoubleArrayAsList(double[] array, int start, int end) { 424 this.array = array; 425 this.start = start; 426 this.end = end; 427 } 428 429 @Override public int size() { 430 return end - start; 431 } 432 433 @Override public boolean isEmpty() { 434 return false; 435 } 436 437 @Override public Double get(int index) { 438 checkElementIndex(index, size()); 439 return array[start + index]; 440 } 441 442 @Override public boolean contains(Object target) { 443 // Overridden to prevent a ton of boxing 444 return (target instanceof Double) 445 && Doubles.indexOf(array, (Double) target, start, end) != -1; 446 } 447 448 @Override public int indexOf(Object target) { 449 // Overridden to prevent a ton of boxing 450 if (target instanceof Double) { 451 int i = Doubles.indexOf(array, (Double) target, start, end); 452 if (i >= 0) { 453 return i - start; 454 } 455 } 456 return -1; 457 } 458 459 @Override public int lastIndexOf(Object target) { 460 // Overridden to prevent a ton of boxing 461 if (target instanceof Double) { 462 int i = Doubles.lastIndexOf(array, (Double) target, start, end); 463 if (i >= 0) { 464 return i - start; 465 } 466 } 467 return -1; 468 } 469 470 @Override public Double set(int index, Double element) { 471 checkElementIndex(index, size()); 472 double oldValue = array[start + index]; 473 array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) 474 return oldValue; 475 } 476 477 @Override public List<Double> subList(int fromIndex, int toIndex) { 478 int size = size(); 479 checkPositionIndexes(fromIndex, toIndex, size); 480 if (fromIndex == toIndex) { 481 return Collections.emptyList(); 482 } 483 return new DoubleArrayAsList(array, start + fromIndex, start + toIndex); 484 } 485 486 @Override public boolean equals(Object object) { 487 if (object == this) { 488 return true; 489 } 490 if (object instanceof DoubleArrayAsList) { 491 DoubleArrayAsList that = (DoubleArrayAsList) object; 492 int size = size(); 493 if (that.size() != size) { 494 return false; 495 } 496 for (int i = 0; i < size; i++) { 497 if (array[start + i] != that.array[that.start + i]) { 498 return false; 499 } 500 } 501 return true; 502 } 503 return super.equals(object); 504 } 505 506 @Override public int hashCode() { 507 int result = 1; 508 for (int i = start; i < end; i++) { 509 result = 31 * result + Doubles.hashCode(array[i]); 510 } 511 return result; 512 } 513 514 @Override public String toString() { 515 StringBuilder builder = new StringBuilder(size() * 12); 516 builder.append('[').append(array[start]); 517 for (int i = start + 1; i < end; i++) { 518 builder.append(", ").append(array[i]); 519 } 520 return builder.append(']').toString(); 521 } 522 523 double[] toDoubleArray() { 524 // Arrays.copyOfRange() requires Java 6 525 int size = size(); 526 double[] result = new double[size]; 527 System.arraycopy(array, start, result, 0, size); 528 return result; 529 } 530 531 private static final long serialVersionUID = 0; 532 } 533 }