1 /* 2 * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang; 27 import java.util.Random; 28 29 import sun.misc.FloatConsts; 30 import sun.misc.DoubleConsts; 31 32 /** 33 * The class {@code Math} contains methods for performing basic 34 * numeric operations such as the elementary exponential, logarithm, 35 * square root, and trigonometric functions. 36 * 37 * <p>Unlike some of the numeric methods of class 38 * {@code StrictMath}, all implementations of the equivalent 39 * functions of class {@code Math} are not defined to return the 40 * bit-for-bit same results. This relaxation permits 41 * better-performing implementations where strict reproducibility is 42 * not required. 43 * 44 * <p>By default many of the {@code Math} methods simply call 45 * the equivalent method in {@code StrictMath} for their 46 * implementation. Code generators are encouraged to use 47 * platform-specific native libraries or microprocessor instructions, 48 * where available, to provide higher-performance implementations of 49 * {@code Math} methods. Such higher-performance 50 * implementations still must conform to the specification for 51 * {@code Math}. 52 * 53 * <p>The quality of implementation specifications concern two 54 * properties, accuracy of the returned result and monotonicity of the 55 * method. Accuracy of the floating-point {@code Math} methods is 56 * measured in terms of <i>ulps</i>, units in the last place. For a 57 * given floating-point format, an {@linkplain #ulp(double) ulp} of a 58 * specific real number value is the distance between the two 59 * floating-point values bracketing that numerical value. When 60 * discussing the accuracy of a method as a whole rather than at a 61 * specific argument, the number of ulps cited is for the worst-case 62 * error at any argument. If a method always has an error less than 63 * 0.5 ulps, the method always returns the floating-point number 64 * nearest the exact result; such a method is <i>correctly 65 * rounded</i>. A correctly rounded method is generally the best a 66 * floating-point approximation can be; however, it is impractical for 67 * many floating-point methods to be correctly rounded. Instead, for 68 * the {@code Math} class, a larger error bound of 1 or 2 ulps is 69 * allowed for certain methods. Informally, with a 1 ulp error bound, 70 * when the exact result is a representable number, the exact result 71 * should be returned as the computed result; otherwise, either of the 72 * two floating-point values which bracket the exact result may be 73 * returned. For exact results large in magnitude, one of the 74 * endpoints of the bracket may be infinite. Besides accuracy at 75 * individual arguments, maintaining proper relations between the 76 * method at different arguments is also important. Therefore, most 77 * methods with more than 0.5 ulp errors are required to be 78 * <i>semi-monotonic</i>: whenever the mathematical function is 79 * non-decreasing, so is the floating-point approximation, likewise, 80 * whenever the mathematical function is non-increasing, so is the 81 * floating-point approximation. Not all approximations that have 1 82 * ulp accuracy will automatically meet the monotonicity requirements. 83 * 84 * <p> 85 * The platform uses signed two's complement integer arithmetic with 86 * int and long primitive types. The developer should choose 87 * the primitive type to ensure that arithmetic operations consistently 88 * produce correct results, which in some cases means the operations 89 * will not overflow the range of values of the computation. 90 * The best practice is to choose the primitive type and algorithm to avoid 91 * overflow. In cases where the size is {@code int} or {@code long} and 92 * overflow errors need to be detected, the methods {@code addExact}, 93 * {@code subtractExact}, {@code multiplyExact}, and {@code toIntExact} 94 * throw an {@code ArithmeticException} when the results overflow. 95 * For other arithmetic operations such as divide, absolute value, 96 * increment, decrement, and negation overflow occurs only with 97 * a specific minimum or maximum value and should be checked against 98 * the minimum or maximum as appropriate. 99 * 100 * @author unascribed 101 * @author Joseph D. Darcy 102 * @since JDK1.0 103 */ 104 105 public final class Math { 106 107 /** 108 * Don't let anyone instantiate this class. 109 */ 110 private Math() {} 111 112 /** 113 * The {@code double} value that is closer than any other to 114 * <i>e</i>, the base of the natural logarithms. 115 */ 116 public static final double E = 2.7182818284590452354; 117 118 /** 119 * The {@code double} value that is closer than any other to 120 * <i>pi</i>, the ratio of the circumference of a circle to its 121 * diameter. 122 */ 123 public static final double PI = 3.14159265358979323846; 124 125 /** 126 * Returns the trigonometric sine of an angle. Special cases: 127 * <ul><li>If the argument is NaN or an infinity, then the 128 * result is NaN. 129 * <li>If the argument is zero, then the result is a zero with the 130 * same sign as the argument.</ul> 131 * 132 * <p>The computed result must be within 1 ulp of the exact result. 133 * Results must be semi-monotonic. 134 * 135 * @param a an angle, in radians. 136 * @return the sine of the argument. 137 */ 138 public static double sin(double a) { 139 return StrictMath.sin(a); // default impl. delegates to StrictMath 140 } 141 142 /** 143 * Returns the trigonometric cosine of an angle. Special cases: 144 * <ul><li>If the argument is NaN or an infinity, then the 145 * result is NaN.</ul> 146 * 147 * <p>The computed result must be within 1 ulp of the exact result. 148 * Results must be semi-monotonic. 149 * 150 * @param a an angle, in radians. 151 * @return the cosine of the argument. 152 */ 153 public static double cos(double a) { 154 return StrictMath.cos(a); // default impl. delegates to StrictMath 155 } 156 157 /** 158 * Returns the trigonometric tangent of an angle. Special cases: 159 * <ul><li>If the argument is NaN or an infinity, then the result 160 * is NaN. 161 * <li>If the argument is zero, then the result is a zero with the 162 * same sign as the argument.</ul> 163 * 164 * <p>The computed result must be within 1 ulp of the exact result. 165 * Results must be semi-monotonic. 166 * 167 * @param a an angle, in radians. 168 * @return the tangent of the argument. 169 */ 170 public static double tan(double a) { 171 return StrictMath.tan(a); // default impl. delegates to StrictMath 172 } 173 174 /** 175 * Returns the arc sine of a value; the returned angle is in the 176 * range -<i>pi</i>/2 through <i>pi</i>/2. Special cases: 177 * <ul><li>If the argument is NaN or its absolute value is greater 178 * than 1, then the result is NaN. 179 * <li>If the argument is zero, then the result is a zero with the 180 * same sign as the argument.</ul> 181 * 182 * <p>The computed result must be within 1 ulp of the exact result. 183 * Results must be semi-monotonic. 184 * 185 * @param a the value whose arc sine is to be returned. 186 * @return the arc sine of the argument. 187 */ 188 public static double asin(double a) { 189 return StrictMath.asin(a); // default impl. delegates to StrictMath 190 } 191 192 /** 193 * Returns the arc cosine of a value; the returned angle is in the 194 * range 0.0 through <i>pi</i>. Special case: 195 * <ul><li>If the argument is NaN or its absolute value is greater 196 * than 1, then the result is NaN.</ul> 197 * 198 * <p>The computed result must be within 1 ulp of the exact result. 199 * Results must be semi-monotonic. 200 * 201 * @param a the value whose arc cosine is to be returned. 202 * @return the arc cosine of the argument. 203 */ 204 public static double acos(double a) { 205 return StrictMath.acos(a); // default impl. delegates to StrictMath 206 } 207 208 /** 209 * Returns the arc tangent of a value; the returned angle is in the 210 * range -<i>pi</i>/2 through <i>pi</i>/2. Special cases: 211 * <ul><li>If the argument is NaN, then the result is NaN. 212 * <li>If the argument is zero, then the result is a zero with the 213 * same sign as the argument.</ul> 214 * 215 * <p>The computed result must be within 1 ulp of the exact result. 216 * Results must be semi-monotonic. 217 * 218 * @param a the value whose arc tangent is to be returned. 219 * @return the arc tangent of the argument. 220 */ 221 public static double atan(double a) { 222 return StrictMath.atan(a); // default impl. delegates to StrictMath 223 } 224 225 /** 226 * Converts an angle measured in degrees to an approximately 227 * equivalent angle measured in radians. The conversion from 228 * degrees to radians is generally inexact. 229 * 230 * @param angdeg an angle, in degrees 231 * @return the measurement of the angle {@code angdeg} 232 * in radians. 233 * @since 1.2 234 */ 235 public static double toRadians(double angdeg) { 236 return angdeg / 180.0 * PI; 237 } 238 239 /** 240 * Converts an angle measured in radians to an approximately 241 * equivalent angle measured in degrees. The conversion from 242 * radians to degrees is generally inexact; users should 243 * <i>not</i> expect {@code cos(toRadians(90.0))} to exactly 244 * equal {@code 0.0}. 245 * 246 * @param angrad an angle, in radians 247 * @return the measurement of the angle {@code angrad} 248 * in degrees. 249 * @since 1.2 250 */ 251 public static double toDegrees(double angrad) { 252 return angrad * 180.0 / PI; 253 } 254 255 /** 256 * Returns Euler's number <i>e</i> raised to the power of a 257 * {@code double} value. Special cases: 258 * <ul><li>If the argument is NaN, the result is NaN. 259 * <li>If the argument is positive infinity, then the result is 260 * positive infinity. 261 * <li>If the argument is negative infinity, then the result is 262 * positive zero.</ul> 263 * 264 * <p>The computed result must be within 1 ulp of the exact result. 265 * Results must be semi-monotonic. 266 * 267 * @param a the exponent to raise <i>e</i> to. 268 * @return the value <i>e</i><sup>{@code a}</sup>, 269 * where <i>e</i> is the base of the natural logarithms. 270 */ 271 public static double exp(double a) { 272 return StrictMath.exp(a); // default impl. delegates to StrictMath 273 } 274 275 /** 276 * Returns the natural logarithm (base <i>e</i>) of a {@code double} 277 * value. Special cases: 278 * <ul><li>If the argument is NaN or less than zero, then the result 279 * is NaN. 280 * <li>If the argument is positive infinity, then the result is 281 * positive infinity. 282 * <li>If the argument is positive zero or negative zero, then the 283 * result is negative infinity.</ul> 284 * 285 * <p>The computed result must be within 1 ulp of the exact result. 286 * Results must be semi-monotonic. 287 * 288 * @param a a value 289 * @return the value ln {@code a}, the natural logarithm of 290 * {@code a}. 291 */ 292 public static double log(double a) { 293 return StrictMath.log(a); // default impl. delegates to StrictMath 294 } 295 296 /** 297 * Returns the base 10 logarithm of a {@code double} value. 298 * Special cases: 299 * 300 * <ul><li>If the argument is NaN or less than zero, then the result 301 * is NaN. 302 * <li>If the argument is positive infinity, then the result is 303 * positive infinity. 304 * <li>If the argument is positive zero or negative zero, then the 305 * result is negative infinity. 306 * <li> If the argument is equal to 10<sup><i>n</i></sup> for 307 * integer <i>n</i>, then the result is <i>n</i>. 308 * </ul> 309 * 310 * <p>The computed result must be within 1 ulp of the exact result. 311 * Results must be semi-monotonic. 312 * 313 * @param a a value 314 * @return the base 10 logarithm of {@code a}. 315 * @since 1.5 316 */ 317 public static double log10(double a) { 318 return StrictMath.log10(a); // default impl. delegates to StrictMath 319 } 320 321 /** 322 * Returns the correctly rounded positive square root of a 323 * {@code double} value. 324 * Special cases: 325 * <ul><li>If the argument is NaN or less than zero, then the result 326 * is NaN. 327 * <li>If the argument is positive infinity, then the result is positive 328 * infinity. 329 * <li>If the argument is positive zero or negative zero, then the 330 * result is the same as the argument.</ul> 331 * Otherwise, the result is the {@code double} value closest to 332 * the true mathematical square root of the argument value. 333 * 334 * @param a a value. 335 * @return the positive square root of {@code a}. 336 * If the argument is NaN or less than zero, the result is NaN. 337 */ 338 public static double sqrt(double a) { 339 return StrictMath.sqrt(a); // default impl. delegates to StrictMath 340 // Note that hardware sqrt instructions 341 // frequently can be directly used by JITs 342 // and should be much faster than doing 343 // Math.sqrt in software. 344 } 345 346 347 /** 348 * Returns the cube root of a {@code double} value. For 349 * positive finite {@code x}, {@code cbrt(-x) == 350 * -cbrt(x)}; that is, the cube root of a negative value is 351 * the negative of the cube root of that value's magnitude. 352 * 353 * Special cases: 354 * 355 * <ul> 356 * 357 * <li>If the argument is NaN, then the result is NaN. 358 * 359 * <li>If the argument is infinite, then the result is an infinity 360 * with the same sign as the argument. 361 * 362 * <li>If the argument is zero, then the result is a zero with the 363 * same sign as the argument. 364 * 365 * </ul> 366 * 367 * <p>The computed result must be within 1 ulp of the exact result. 368 * 369 * @param a a value. 370 * @return the cube root of {@code a}. 371 * @since 1.5 372 */ 373 public static double cbrt(double a) { 374 return StrictMath.cbrt(a); 375 } 376 377 /** 378 * Computes the remainder operation on two arguments as prescribed 379 * by the IEEE 754 standard. 380 * The remainder value is mathematically equal to 381 * <code>f1 - f2</code> × <i>n</i>, 382 * where <i>n</i> is the mathematical integer closest to the exact 383 * mathematical value of the quotient {@code f1/f2}, and if two 384 * mathematical integers are equally close to {@code f1/f2}, 385 * then <i>n</i> is the integer that is even. If the remainder is 386 * zero, its sign is the same as the sign of the first argument. 387 * Special cases: 388 * <ul><li>If either argument is NaN, or the first argument is infinite, 389 * or the second argument is positive zero or negative zero, then the 390 * result is NaN. 391 * <li>If the first argument is finite and the second argument is 392 * infinite, then the result is the same as the first argument.</ul> 393 * 394 * @param f1 the dividend. 395 * @param f2 the divisor. 396 * @return the remainder when {@code f1} is divided by 397 * {@code f2}. 398 */ 399 public static double IEEEremainder(double f1, double f2) { 400 return StrictMath.IEEEremainder(f1, f2); // delegate to StrictMath 401 } 402 403 /** 404 * Returns the smallest (closest to negative infinity) 405 * {@code double} value that is greater than or equal to the 406 * argument and is equal to a mathematical integer. Special cases: 407 * <ul><li>If the argument value is already equal to a 408 * mathematical integer, then the result is the same as the 409 * argument. <li>If the argument is NaN or an infinity or 410 * positive zero or negative zero, then the result is the same as 411 * the argument. <li>If the argument value is less than zero but 412 * greater than -1.0, then the result is negative zero.</ul> Note 413 * that the value of {@code Math.ceil(x)} is exactly the 414 * value of {@code -Math.floor(-x)}. 415 * 416 * 417 * @param a a value. 418 * @return the smallest (closest to negative infinity) 419 * floating-point value that is greater than or equal to 420 * the argument and is equal to a mathematical integer. 421 */ 422 public static double ceil(double a) { 423 return StrictMath.ceil(a); // default impl. delegates to StrictMath 424 } 425 426 /** 427 * Returns the largest (closest to positive infinity) 428 * {@code double} value that is less than or equal to the 429 * argument and is equal to a mathematical integer. Special cases: 430 * <ul><li>If the argument value is already equal to a 431 * mathematical integer, then the result is the same as the 432 * argument. <li>If the argument is NaN or an infinity or 433 * positive zero or negative zero, then the result is the same as 434 * the argument.</ul> 435 * 436 * @param a a value. 437 * @return the largest (closest to positive infinity) 438 * floating-point value that less than or equal to the argument 439 * and is equal to a mathematical integer. 440 */ 441 public static double floor(double a) { 442 return StrictMath.floor(a); // default impl. delegates to StrictMath 443 } 444 445 /** 446 * Returns the {@code double} value that is closest in value 447 * to the argument and is equal to a mathematical integer. If two 448 * {@code double} values that are mathematical integers are 449 * equally close, the result is the integer value that is 450 * even. Special cases: 451 * <ul><li>If the argument value is already equal to a mathematical 452 * integer, then the result is the same as the argument. 453 * <li>If the argument is NaN or an infinity or positive zero or negative 454 * zero, then the result is the same as the argument.</ul> 455 * 456 * @param a a {@code double} value. 457 * @return the closest floating-point value to {@code a} that is 458 * equal to a mathematical integer. 459 */ 460 public static double rint(double a) { 461 return StrictMath.rint(a); // default impl. delegates to StrictMath 462 } 463 464 /** 465 * Returns the angle <i>theta</i> from the conversion of rectangular 466 * coordinates ({@code x}, {@code y}) to polar 467 * coordinates (r, <i>theta</i>). 468 * This method computes the phase <i>theta</i> by computing an arc tangent 469 * of {@code y/x} in the range of -<i>pi</i> to <i>pi</i>. Special 470 * cases: 471 * <ul><li>If either argument is NaN, then the result is NaN. 472 * <li>If the first argument is positive zero and the second argument 473 * is positive, or the first argument is positive and finite and the 474 * second argument is positive infinity, then the result is positive 475 * zero. 476 * <li>If the first argument is negative zero and the second argument 477 * is positive, or the first argument is negative and finite and the 478 * second argument is positive infinity, then the result is negative zero. 479 * <li>If the first argument is positive zero and the second argument 480 * is negative, or the first argument is positive and finite and the 481 * second argument is negative infinity, then the result is the 482 * {@code double} value closest to <i>pi</i>. 483 * <li>If the first argument is negative zero and the second argument 484 * is negative, or the first argument is negative and finite and the 485 * second argument is negative infinity, then the result is the 486 * {@code double} value closest to -<i>pi</i>. 487 * <li>If the first argument is positive and the second argument is 488 * positive zero or negative zero, or the first argument is positive 489 * infinity and the second argument is finite, then the result is the 490 * {@code double} value closest to <i>pi</i>/2. 491 * <li>If the first argument is negative and the second argument is 492 * positive zero or negative zero, or the first argument is negative 493 * infinity and the second argument is finite, then the result is the 494 * {@code double} value closest to -<i>pi</i>/2. 495 * <li>If both arguments are positive infinity, then the result is the 496 * {@code double} value closest to <i>pi</i>/4. 497 * <li>If the first argument is positive infinity and the second argument 498 * is negative infinity, then the result is the {@code double} 499 * value closest to 3*<i>pi</i>/4. 500 * <li>If the first argument is negative infinity and the second argument 501 * is positive infinity, then the result is the {@code double} value 502 * closest to -<i>pi</i>/4. 503 * <li>If both arguments are negative infinity, then the result is the 504 * {@code double} value closest to -3*<i>pi</i>/4.</ul> 505 * 506 * <p>The computed result must be within 2 ulps of the exact result. 507 * Results must be semi-monotonic. 508 * 509 * @param y the ordinate coordinate 510 * @param x the abscissa coordinate 511 * @return the <i>theta</i> component of the point 512 * (<i>r</i>, <i>theta</i>) 513 * in polar coordinates that corresponds to the point 514 * (<i>x</i>, <i>y</i>) in Cartesian coordinates. 515 */ 516 public static double atan2(double y, double x) { 517 return StrictMath.atan2(y, x); // default impl. delegates to StrictMath 518 } 519 520 /** 521 * Returns the value of the first argument raised to the power of the 522 * second argument. Special cases: 523 * 524 * <ul><li>If the second argument is positive or negative zero, then the 525 * result is 1.0. 526 * <li>If the second argument is 1.0, then the result is the same as the 527 * first argument. 528 * <li>If the second argument is NaN, then the result is NaN. 529 * <li>If the first argument is NaN and the second argument is nonzero, 530 * then the result is NaN. 531 * 532 * <li>If 533 * <ul> 534 * <li>the absolute value of the first argument is greater than 1 535 * and the second argument is positive infinity, or 536 * <li>the absolute value of the first argument is less than 1 and 537 * the second argument is negative infinity, 538 * </ul> 539 * then the result is positive infinity. 540 * 541 * <li>If 542 * <ul> 543 * <li>the absolute value of the first argument is greater than 1 and 544 * the second argument is negative infinity, or 545 * <li>the absolute value of the 546 * first argument is less than 1 and the second argument is positive 547 * infinity, 548 * </ul> 549 * then the result is positive zero. 550 * 551 * <li>If the absolute value of the first argument equals 1 and the 552 * second argument is infinite, then the result is NaN. 553 * 554 * <li>If 555 * <ul> 556 * <li>the first argument is positive zero and the second argument 557 * is greater than zero, or 558 * <li>the first argument is positive infinity and the second 559 * argument is less than zero, 560 * </ul> 561 * then the result is positive zero. 562 * 563 * <li>If 564 * <ul> 565 * <li>the first argument is positive zero and the second argument 566 * is less than zero, or 567 * <li>the first argument is positive infinity and the second 568 * argument is greater than zero, 569 * </ul> 570 * then the result is positive infinity. 571 * 572 * <li>If 573 * <ul> 574 * <li>the first argument is negative zero and the second argument 575 * is greater than zero but not a finite odd integer, or 576 * <li>the first argument is negative infinity and the second 577 * argument is less than zero but not a finite odd integer, 578 * </ul> 579 * then the result is positive zero. 580 * 581 * <li>If 582 * <ul> 583 * <li>the first argument is negative zero and the second argument 584 * is a positive finite odd integer, or 585 * <li>the first argument is negative infinity and the second 586 * argument is a negative finite odd integer, 587 * </ul> 588 * then the result is negative zero. 589 * 590 * <li>If 591 * <ul> 592 * <li>the first argument is negative zero and the second argument 593 * is less than zero but not a finite odd integer, or 594 * <li>the first argument is negative infinity and the second 595 * argument is greater than zero but not a finite odd integer, 596 * </ul> 597 * then the result is positive infinity. 598 * 599 * <li>If 600 * <ul> 601 * <li>the first argument is negative zero and the second argument 602 * is a negative finite odd integer, or 603 * <li>the first argument is negative infinity and the second 604 * argument is a positive finite odd integer, 605 * </ul> 606 * then the result is negative infinity. 607 * 608 * <li>If the first argument is finite and less than zero 609 * <ul> 610 * <li> if the second argument is a finite even integer, the 611 * result is equal to the result of raising the absolute value of 612 * the first argument to the power of the second argument 613 * 614 * <li>if the second argument is a finite odd integer, the result 615 * is equal to the negative of the result of raising the absolute 616 * value of the first argument to the power of the second 617 * argument 618 * 619 * <li>if the second argument is finite and not an integer, then 620 * the result is NaN. 621 * </ul> 622 * 623 * <li>If both arguments are integers, then the result is exactly equal 624 * to the mathematical result of raising the first argument to the power 625 * of the second argument if that result can in fact be represented 626 * exactly as a {@code double} value.</ul> 627 * 628 * <p>(In the foregoing descriptions, a floating-point value is 629 * considered to be an integer if and only if it is finite and a 630 * fixed point of the method {@link #ceil ceil} or, 631 * equivalently, a fixed point of the method {@link #floor 632 * floor}. A value is a fixed point of a one-argument 633 * method if and only if the result of applying the method to the 634 * value is equal to the value.) 635 * 636 * <p>The computed result must be within 1 ulp of the exact result. 637 * Results must be semi-monotonic. 638 * 639 * @param a the base. 640 * @param b the exponent. 641 * @return the value {@code a}<sup>{@code b}</sup>. 642 */ 643 public static double pow(double a, double b) { 644 return StrictMath.pow(a, b); // default impl. delegates to StrictMath 645 } 646 647 /** 648 * Returns the closest {@code int} to the argument, with ties 649 * rounding to positive infinity. 650 * 651 * <p> 652 * Special cases: 653 * <ul><li>If the argument is NaN, the result is 0. 654 * <li>If the argument is negative infinity or any value less than or 655 * equal to the value of {@code Integer.MIN_VALUE}, the result is 656 * equal to the value of {@code Integer.MIN_VALUE}. 657 * <li>If the argument is positive infinity or any value greater than or 658 * equal to the value of {@code Integer.MAX_VALUE}, the result is 659 * equal to the value of {@code Integer.MAX_VALUE}.</ul> 660 * 661 * @param a a floating-point value to be rounded to an integer. 662 * @return the value of the argument rounded to the nearest 663 * {@code int} value. 664 * @see java.lang.Integer#MAX_VALUE 665 * @see java.lang.Integer#MIN_VALUE 666 */ 667 public static int round(float a) { 668 int intBits = Float.floatToRawIntBits(a); 669 int biasedExp = (intBits & FloatConsts.EXP_BIT_MASK) 670 >> (FloatConsts.SIGNIFICAND_WIDTH - 1); 671 int shift = (FloatConsts.SIGNIFICAND_WIDTH - 2 672 + FloatConsts.EXP_BIAS) - biasedExp; 673 if ((shift & -32) == 0) { // shift >= 0 && shift < 32 674 // a is a finite number such that pow(2,-32) <= ulp(a) < 1 675 int r = ((intBits & FloatConsts.SIGNIF_BIT_MASK) 676 | (FloatConsts.SIGNIF_BIT_MASK + 1)); 677 if (intBits < 0) { 678 r = -r; 679 } 680 // In the comments below each Java expression evaluates to the value 681 // the corresponding mathematical expression: 682 // (r) evaluates to a / ulp(a) 683 // (r >> shift) evaluates to floor(a * 2) 684 // ((r >> shift) + 1) evaluates to floor((a + 1/2) * 2) 685 // (((r >> shift) + 1) >> 1) evaluates to floor(a + 1/2) 686 return ((r >> shift) + 1) >> 1; 687 } else { 688 // a is either 689 // - a finite number with abs(a) < exp(2,FloatConsts.SIGNIFICAND_WIDTH-32) < 1/2 690 // - a finite number with ulp(a) >= 1 and hence a is a mathematical integer 691 // - an infinity or NaN 692 return (int) a; 693 } 694 } 695 696 /** 697 * Returns the closest {@code long} to the argument, with ties 698 * rounding to positive infinity. 699 * 700 * <p>Special cases: 701 * <ul><li>If the argument is NaN, the result is 0. 702 * <li>If the argument is negative infinity or any value less than or 703 * equal to the value of {@code Long.MIN_VALUE}, the result is 704 * equal to the value of {@code Long.MIN_VALUE}. 705 * <li>If the argument is positive infinity or any value greater than or 706 * equal to the value of {@code Long.MAX_VALUE}, the result is 707 * equal to the value of {@code Long.MAX_VALUE}.</ul> 708 * 709 * @param a a floating-point value to be rounded to a 710 * {@code long}. 711 * @return the value of the argument rounded to the nearest 712 * {@code long} value. 713 * @see java.lang.Long#MAX_VALUE 714 * @see java.lang.Long#MIN_VALUE 715 */ 716 public static long round(double a) { 717 long longBits = Double.doubleToRawLongBits(a); 718 long biasedExp = (longBits & DoubleConsts.EXP_BIT_MASK) 719 >> (DoubleConsts.SIGNIFICAND_WIDTH - 1); 720 long shift = (DoubleConsts.SIGNIFICAND_WIDTH - 2 721 + DoubleConsts.EXP_BIAS) - biasedExp; 722 if ((shift & -64) == 0) { // shift >= 0 && shift < 64 723 // a is a finite number such that pow(2,-64) <= ulp(a) < 1 724 long r = ((longBits & DoubleConsts.SIGNIF_BIT_MASK) 725 | (DoubleConsts.SIGNIF_BIT_MASK + 1)); 726 if (longBits < 0) { 727 r = -r; 728 } 729 // In the comments below each Java expression evaluates to the value 730 // the corresponding mathematical expression: 731 // (r) evaluates to a / ulp(a) 732 // (r >> shift) evaluates to floor(a * 2) 733 // ((r >> shift) + 1) evaluates to floor((a + 1/2) * 2) 734 // (((r >> shift) + 1) >> 1) evaluates to floor(a + 1/2) 735 return ((r >> shift) + 1) >> 1; 736 } else { 737 // a is either 738 // - a finite number with abs(a) < exp(2,DoubleConsts.SIGNIFICAND_WIDTH-64) < 1/2 739 // - a finite number with ulp(a) >= 1 and hence a is a mathematical integer 740 // - an infinity or NaN 741 return (long) a; 742 } 743 } 744 745 private static final class RandomNumberGeneratorHolder { 746 static final Random randomNumberGenerator = new Random(); 747 } 748 749 /** 750 * Returns a {@code double} value with a positive sign, greater 751 * than or equal to {@code 0.0} and less than {@code 1.0}. 752 * Returned values are chosen pseudorandomly with (approximately) 753 * uniform distribution from that range. 754 * 755 * <p>When this method is first called, it creates a single new 756 * pseudorandom-number generator, exactly as if by the expression 757 * 758 * <blockquote>{@code new java.util.Random()}</blockquote> 759 * 760 * This new pseudorandom-number generator is used thereafter for 761 * all calls to this method and is used nowhere else. 762 * 763 * <p>This method is properly synchronized to allow correct use by 764 * more than one thread. However, if many threads need to generate 765 * pseudorandom numbers at a great rate, it may reduce contention 766 * for each thread to have its own pseudorandom-number generator. 767 * 768 * @apiNote 769 * As the largest {@code double} value less than {@code 1.0} 770 * is {@code Math.nextDown(1.0)}, a value {@code x} in the closed range 771 * {@code [x1,x2]} where {@code x1<=x2} may be defined by the statements 772 * 773 * <blockquote><pre>{@code 774 * double f = Math.random()/Math.nextDown(1.0); 775 * double x = x1*(1.0 - f) + x2*f; 776 * }</pre></blockquote> 777 * 778 * @return a pseudorandom {@code double} greater than or equal 779 * to {@code 0.0} and less than {@code 1.0}. 780 * @see #nextDown(double) 781 * @see Random#nextDouble() 782 */ 783 public static double random() { 784 return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble(); 785 } 786 787 /** 788 * Returns the sum of its arguments, 789 * throwing an exception if the result overflows an {@code int}. 790 * 791 * @param x the first value 792 * @param y the second value 793 * @return the result 794 * @throws ArithmeticException if the result overflows an int 795 * @since 1.8 796 */ 797 public static int addExact(int x, int y) { 798 int r = x + y; 799 // HD 2-12 Overflow iff both arguments have the opposite sign of the result 800 if (((x ^ r) & (y ^ r)) < 0) { 801 throw new ArithmeticException("integer overflow"); 802 } 803 return r; 804 } 805 806 /** 807 * Returns the sum of its arguments, 808 * throwing an exception if the result overflows a {@code long}. 809 * 810 * @param x the first value 811 * @param y the second value 812 * @return the result 813 * @throws ArithmeticException if the result overflows a long 814 * @since 1.8 815 */ 816 public static long addExact(long x, long y) { 817 long r = x + y; 818 // HD 2-12 Overflow iff both arguments have the opposite sign of the result 819 if (((x ^ r) & (y ^ r)) < 0) { 820 throw new ArithmeticException("long overflow"); 821 } 822 return r; 823 } 824 825 /** 826 * Returns the difference of the arguments, 827 * throwing an exception if the result overflows an {@code int}. 828 * 829 * @param x the first value 830 * @param y the second value to subtract from the first 831 * @return the result 832 * @throws ArithmeticException if the result overflows an int 833 * @since 1.8 834 */ 835 public static int subtractExact(int x, int y) { 836 int r = x - y; 837 // HD 2-12 Overflow iff the arguments have different signs and 838 // the sign of the result is different than the sign of x 839 if (((x ^ y) & (x ^ r)) < 0) { 840 throw new ArithmeticException("integer overflow"); 841 } 842 return r; 843 } 844 845 /** 846 * Returns the difference of the arguments, 847 * throwing an exception if the result overflows a {@code long}. 848 * 849 * @param x the first value 850 * @param y the second value to subtract from the first 851 * @return the result 852 * @throws ArithmeticException if the result overflows a long 853 * @since 1.8 854 */ 855 public static long subtractExact(long x, long y) { 856 long r = x - y; 857 // HD 2-12 Overflow iff the arguments have different signs and 858 // the sign of the result is different than the sign of x 859 if (((x ^ y) & (x ^ r)) < 0) { 860 throw new ArithmeticException("long overflow"); 861 } 862 return r; 863 } 864 865 /** 866 * Returns the product of the arguments, 867 * throwing an exception if the result overflows an {@code int}. 868 * 869 * @param x the first value 870 * @param y the second value 871 * @return the result 872 * @throws ArithmeticException if the result overflows an int 873 * @since 1.8 874 */ 875 public static int multiplyExact(int x, int y) { 876 long r = (long)x * (long)y; 877 if ((int)r != r) { 878 throw new ArithmeticException("integer overflow"); 879 } 880 return (int)r; 881 } 882 883 /** 884 * Returns the product of the arguments, 885 * throwing an exception if the result overflows a {@code long}. 886 * 887 * @param x the first value 888 * @param y the second value 889 * @return the result 890 * @throws ArithmeticException if the result overflows a long 891 * @since 1.8 892 */ 893 public static long multiplyExact(long x, long y) { 894 long r = x * y; 895 long ax = Math.abs(x); 896 long ay = Math.abs(y); 897 if (((ax | ay) >>> 31 != 0)) { 898 // Some bits greater than 2^31 that might cause overflow 899 // Check the result using the divide operator 900 // and check for the special case of Long.MIN_VALUE * -1 901 if (((y != 0) && (r / y != x)) || 902 (x == Long.MIN_VALUE && y == -1)) { 903 throw new ArithmeticException("long overflow"); 904 } 905 } 906 return r; 907 } 908 909 /** 910 * Returns the argument incremented by one, throwing an exception if the 911 * result overflows an {@code int}. 912 * 913 * @param a the value to increment 914 * @return the result 915 * @throws ArithmeticException if the result overflows an int 916 * @since 1.8 917 */ 918 public static int incrementExact(int a) { 919 if (a == Integer.MAX_VALUE) { 920 throw new ArithmeticException("integer overflow"); 921 } 922 923 return a + 1; 924 } 925 926 /** 927 * Returns the argument incremented by one, throwing an exception if the 928 * result overflows a {@code long}. 929 * 930 * @param a the value to increment 931 * @return the result 932 * @throws ArithmeticException if the result overflows a long 933 * @since 1.8 934 */ 935 public static long incrementExact(long a) { 936 if (a == Long.MAX_VALUE) { 937 throw new ArithmeticException("long overflow"); 938 } 939 940 return a + 1L; 941 } 942 943 /** 944 * Returns the argument decremented by one, throwing an exception if the 945 * result overflows an {@code int}. 946 * 947 * @param a the value to decrement 948 * @return the result 949 * @throws ArithmeticException if the result overflows an int 950 * @since 1.8 951 */ 952 public static int decrementExact(int a) { 953 if (a == Integer.MIN_VALUE) { 954 throw new ArithmeticException("integer overflow"); 955 } 956 957 return a - 1; 958 } 959 960 /** 961 * Returns the argument decremented by one, throwing an exception if the 962 * result overflows a {@code long}. 963 * 964 * @param a the value to decrement 965 * @return the result 966 * @throws ArithmeticException if the result overflows a long 967 * @since 1.8 968 */ 969 public static long decrementExact(long a) { 970 if (a == Long.MIN_VALUE) { 971 throw new ArithmeticException("long overflow"); 972 } 973 974 return a - 1L; 975 } 976 977 /** 978 * Returns the negation of the argument, throwing an exception if the 979 * result overflows an {@code int}. 980 * 981 * @param a the value to negate 982 * @return the result 983 * @throws ArithmeticException if the result overflows an int 984 * @since 1.8 985 */ 986 public static int negateExact(int a) { 987 if (a == Integer.MIN_VALUE) { 988 throw new ArithmeticException("integer overflow"); 989 } 990 991 return -a; 992 } 993 994 /** 995 * Returns the negation of the argument, throwing an exception if the 996 * result overflows a {@code long}. 997 * 998 * @param a the value to negate 999 * @return the result 1000 * @throws ArithmeticException if the result overflows a long 1001 * @since 1.8 1002 */ 1003 public static long negateExact(long a) { 1004 if (a == Long.MIN_VALUE) { 1005 throw new ArithmeticException("long overflow"); 1006 } 1007 1008 return -a; 1009 } 1010 1011 /** 1012 * Returns the value of the {@code long} argument; 1013 * throwing an exception if the value overflows an {@code int}. 1014 * 1015 * @param value the long value 1016 * @return the argument as an int 1017 * @throws ArithmeticException if the {@code argument} overflows an int 1018 * @since 1.8 1019 */ 1020 public static int toIntExact(long value) { 1021 if ((int)value != value) { 1022 throw new ArithmeticException("integer overflow"); 1023 } 1024 return (int)value; 1025 } 1026 1027 /** 1028 * Returns the largest (closest to positive infinity) 1029 * {@code int} value that is less than or equal to the algebraic quotient. 1030 * There is one special case, if the dividend is the 1031 * {@linkplain Integer#MIN_VALUE Integer.MIN_VALUE} and the divisor is {@code -1}, 1032 * then integer overflow occurs and 1033 * the result is equal to the {@code Integer.MIN_VALUE}. 1034 * <p> 1035 * Normal integer division operates under the round to zero rounding mode 1036 * (truncation). This operation instead acts under the round toward 1037 * negative infinity (floor) rounding mode. 1038 * The floor rounding mode gives different results than truncation 1039 * when the exact result is negative. 1040 * <ul> 1041 * <li>If the signs of the arguments are the same, the results of 1042 * {@code floorDiv} and the {@code /} operator are the same. <br> 1043 * For example, {@code floorDiv(4, 3) == 1} and {@code (4 / 3) == 1}.</li> 1044 * <li>If the signs of the arguments are different, the quotient is negative and 1045 * {@code floorDiv} returns the integer less than or equal to the quotient 1046 * and the {@code /} operator returns the integer closest to zero.<br> 1047 * For example, {@code floorDiv(-4, 3) == -2}, 1048 * whereas {@code (-4 / 3) == -1}. 1049 * </li> 1050 * </ul> 1051 * <p> 1052 * 1053 * @param x the dividend 1054 * @param y the divisor 1055 * @return the largest (closest to positive infinity) 1056 * {@code int} value that is less than or equal to the algebraic quotient. 1057 * @throws ArithmeticException if the divisor {@code y} is zero 1058 * @see #floorMod(int, int) 1059 * @see #floor(double) 1060 * @since 1.8 1061 */ 1062 public static int floorDiv(int x, int y) { 1063 int r = x / y; 1064 // if the signs are different and modulo not zero, round down 1065 if ((x ^ y) < 0 && (r * y != x)) { 1066 r--; 1067 } 1068 return r; 1069 } 1070 1071 /** 1072 * Returns the largest (closest to positive infinity) 1073 * {@code long} value that is less than or equal to the algebraic quotient. 1074 * There is one special case, if the dividend is the 1075 * {@linkplain Long#MIN_VALUE Long.MIN_VALUE} and the divisor is {@code -1}, 1076 * then integer overflow occurs and 1077 * the result is equal to the {@code Long.MIN_VALUE}. 1078 * <p> 1079 * Normal integer division operates under the round to zero rounding mode 1080 * (truncation). This operation instead acts under the round toward 1081 * negative infinity (floor) rounding mode. 1082 * The floor rounding mode gives different results than truncation 1083 * when the exact result is negative. 1084 * <p> 1085 * For examples, see {@link #floorDiv(int, int)}. 1086 * 1087 * @param x the dividend 1088 * @param y the divisor 1089 * @return the largest (closest to positive infinity) 1090 * {@code long} value that is less than or equal to the algebraic quotient. 1091 * @throws ArithmeticException if the divisor {@code y} is zero 1092 * @see #floorMod(long, long) 1093 * @see #floor(double) 1094 * @since 1.8 1095 */ 1096 public static long floorDiv(long x, long y) { 1097 long r = x / y; 1098 // if the signs are different and modulo not zero, round down 1099 if ((x ^ y) < 0 && (r * y != x)) { 1100 r--; 1101 } 1102 return r; 1103 } 1104 1105 /** 1106 * Returns the floor modulus of the {@code int} arguments. 1107 * <p> 1108 * The floor modulus is {@code x - (floorDiv(x, y) * y)}, 1109 * has the same sign as the divisor {@code y}, and 1110 * is in the range of {@code -abs(y) < r < +abs(y)}. 1111 * 1112 * <p> 1113 * The relationship between {@code floorDiv} and {@code floorMod} is such that: 1114 * <ul> 1115 * <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x} 1116 * </ul> 1117 * <p> 1118 * The difference in values between {@code floorMod} and 1119 * the {@code %} operator is due to the difference between 1120 * {@code floorDiv} that returns the integer less than or equal to the quotient 1121 * and the {@code /} operator that returns the integer closest to zero. 1122 * <p> 1123 * Examples: 1124 * <ul> 1125 * <li>If the signs of the arguments are the same, the results 1126 * of {@code floorMod} and the {@code %} operator are the same. <br> 1127 * <ul> 1128 * <li>{@code floorMod(4, 3) == 1}; and {@code (4 % 3) == 1}</li> 1129 * </ul> 1130 * <li>If the signs of the arguments are different, the results differ from the {@code %} operator.<br> 1131 * <ul> 1132 * <li>{@code floorMod(+4, -3) == -2}; and {@code (+4 % -3) == +1} </li> 1133 * <li>{@code floorMod(-4, +3) == +2}; and {@code (-4 % +3) == -1} </li> 1134 * <li>{@code floorMod(-4, -3) == -1}; and {@code (-4 % -3) == -1 } </li> 1135 * </ul> 1136 * </li> 1137 * </ul> 1138 * <p> 1139 * If the signs of arguments are unknown and a positive modulus 1140 * is needed it can be computed as {@code (floorMod(x, y) + abs(y)) % abs(y)}. 1141 * 1142 * @param x the dividend 1143 * @param y the divisor 1144 * @return the floor modulus {@code x - (floorDiv(x, y) * y)} 1145 * @throws ArithmeticException if the divisor {@code y} is zero 1146 * @see #floorDiv(int, int) 1147 * @since 1.8 1148 */ 1149 public static int floorMod(int x, int y) { 1150 int r = x - floorDiv(x, y) * y; 1151 return r; 1152 } 1153 1154 /** 1155 * Returns the floor modulus of the {@code long} arguments. 1156 * <p> 1157 * The floor modulus is {@code x - (floorDiv(x, y) * y)}, 1158 * has the same sign as the divisor {@code y}, and 1159 * is in the range of {@code -abs(y) < r < +abs(y)}. 1160 * 1161 * <p> 1162 * The relationship between {@code floorDiv} and {@code floorMod} is such that: 1163 * <ul> 1164 * <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x} 1165 * </ul> 1166 * <p> 1167 * For examples, see {@link #floorMod(int, int)}. 1168 * 1169 * @param x the dividend 1170 * @param y the divisor 1171 * @return the floor modulus {@code x - (floorDiv(x, y) * y)} 1172 * @throws ArithmeticException if the divisor {@code y} is zero 1173 * @see #floorDiv(long, long) 1174 * @since 1.8 1175 */ 1176 public static long floorMod(long x, long y) { 1177 return x - floorDiv(x, y) * y; 1178 } 1179 1180 /** 1181 * Returns the absolute value of an {@code int} value. 1182 * If the argument is not negative, the argument is returned. 1183 * If the argument is negative, the negation of the argument is returned. 1184 * 1185 * <p>Note that if the argument is equal to the value of 1186 * {@link Integer#MIN_VALUE}, the most negative representable 1187 * {@code int} value, the result is that same value, which is 1188 * negative. 1189 * 1190 * @param a the argument whose absolute value is to be determined 1191 * @return the absolute value of the argument. 1192 */ 1193 public static int abs(int a) { 1194 return (a < 0) ? -a : a; 1195 } 1196 1197 /** 1198 * Returns the absolute value of a {@code long} value. 1199 * If the argument is not negative, the argument is returned. 1200 * If the argument is negative, the negation of the argument is returned. 1201 * 1202 * <p>Note that if the argument is equal to the value of 1203 * {@link Long#MIN_VALUE}, the most negative representable 1204 * {@code long} value, the result is that same value, which 1205 * is negative. 1206 * 1207 * @param a the argument whose absolute value is to be determined 1208 * @return the absolute value of the argument. 1209 */ 1210 public static long abs(long a) { 1211 return (a < 0) ? -a : a; 1212 } 1213 1214 /** 1215 * Returns the absolute value of a {@code float} value. 1216 * If the argument is not negative, the argument is returned. 1217 * If the argument is negative, the negation of the argument is returned. 1218 * Special cases: 1219 * <ul><li>If the argument is positive zero or negative zero, the 1220 * result is positive zero. 1221 * <li>If the argument is infinite, the result is positive infinity. 1222 * <li>If the argument is NaN, the result is NaN.</ul> 1223 * In other words, the result is the same as the value of the expression: 1224 * <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))} 1225 * 1226 * @param a the argument whose absolute value is to be determined 1227 * @return the absolute value of the argument. 1228 */ 1229 public static float abs(float a) { 1230 return (a <= 0.0F) ? 0.0F - a : a; 1231 } 1232 1233 /** 1234 * Returns the absolute value of a {@code double} value. 1235 * If the argument is not negative, the argument is returned. 1236 * If the argument is negative, the negation of the argument is returned. 1237 * Special cases: 1238 * <ul><li>If the argument is positive zero or negative zero, the result 1239 * is positive zero. 1240 * <li>If the argument is infinite, the result is positive infinity. 1241 * <li>If the argument is NaN, the result is NaN.</ul> 1242 * In other words, the result is the same as the value of the expression: 1243 * <p>{@code Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)} 1244 * 1245 * @param a the argument whose absolute value is to be determined 1246 * @return the absolute value of the argument. 1247 */ 1248 public static double abs(double a) { 1249 return (a <= 0.0D) ? 0.0D - a : a; 1250 } 1251 1252 /** 1253 * Returns the greater of two {@code int} values. That is, the 1254 * result is the argument closer to the value of 1255 * {@link Integer#MAX_VALUE}. If the arguments have the same value, 1256 * the result is that same value. 1257 * 1258 * @param a an argument. 1259 * @param b another argument. 1260 * @return the larger of {@code a} and {@code b}. 1261 */ 1262 public static int max(int a, int b) { 1263 return (a >= b) ? a : b; 1264 } 1265 1266 /** 1267 * Returns the greater of two {@code long} values. That is, the 1268 * result is the argument closer to the value of 1269 * {@link Long#MAX_VALUE}. If the arguments have the same value, 1270 * the result is that same value. 1271 * 1272 * @param a an argument. 1273 * @param b another argument. 1274 * @return the larger of {@code a} and {@code b}. 1275 */ 1276 public static long max(long a, long b) { 1277 return (a >= b) ? a : b; 1278 } 1279 1280 // Use raw bit-wise conversions on guaranteed non-NaN arguments. 1281 private static long negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f); 1282 private static long negativeZeroDoubleBits = Double.doubleToRawLongBits(-0.0d); 1283 1284 /** 1285 * Returns the greater of two {@code float} values. That is, 1286 * the result is the argument closer to positive infinity. If the 1287 * arguments have the same value, the result is that same 1288 * value. If either value is NaN, then the result is NaN. Unlike 1289 * the numerical comparison operators, this method considers 1290 * negative zero to be strictly smaller than positive zero. If one 1291 * argument is positive zero and the other negative zero, the 1292 * result is positive zero. 1293 * 1294 * @param a an argument. 1295 * @param b another argument. 1296 * @return the larger of {@code a} and {@code b}. 1297 */ 1298 public static float max(float a, float b) { 1299 if (a != a) 1300 return a; // a is NaN 1301 if ((a == 0.0f) && 1302 (b == 0.0f) && 1303 (Float.floatToRawIntBits(a) == negativeZeroFloatBits)) { 1304 // Raw conversion ok since NaN can't map to -0.0. 1305 return b; 1306 } 1307 return (a >= b) ? a : b; 1308 } 1309 1310 /** 1311 * Returns the greater of two {@code double} values. That 1312 * is, the result is the argument closer to positive infinity. If 1313 * the arguments have the same value, the result is that same 1314 * value. If either value is NaN, then the result is NaN. Unlike 1315 * the numerical comparison operators, this method considers 1316 * negative zero to be strictly smaller than positive zero. If one 1317 * argument is positive zero and the other negative zero, the 1318 * result is positive zero. 1319 * 1320 * @param a an argument. 1321 * @param b another argument. 1322 * @return the larger of {@code a} and {@code b}. 1323 */ 1324 public static double max(double a, double b) { 1325 if (a != a) 1326 return a; // a is NaN 1327 if ((a == 0.0d) && 1328 (b == 0.0d) && 1329 (Double.doubleToRawLongBits(a) == negativeZeroDoubleBits)) { 1330 // Raw conversion ok since NaN can't map to -0.0. 1331 return b; 1332 } 1333 return (a >= b) ? a : b; 1334 } 1335 1336 /** 1337 * Returns the smaller of two {@code int} values. That is, 1338 * the result the argument closer to the value of 1339 * {@link Integer#MIN_VALUE}. If the arguments have the same 1340 * value, the result is that same value. 1341 * 1342 * @param a an argument. 1343 * @param b another argument. 1344 * @return the smaller of {@code a} and {@code b}. 1345 */ 1346 public static int min(int a, int b) { 1347 return (a <= b) ? a : b; 1348 } 1349 1350 /** 1351 * Returns the smaller of two {@code long} values. That is, 1352 * the result is the argument closer to the value of 1353 * {@link Long#MIN_VALUE}. If the arguments have the same 1354 * value, the result is that same value. 1355 * 1356 * @param a an argument. 1357 * @param b another argument. 1358 * @return the smaller of {@code a} and {@code b}. 1359 */ 1360 public static long min(long a, long b) { 1361 return (a <= b) ? a : b; 1362 } 1363 1364 /** 1365 * Returns the smaller of two {@code float} values. That is, 1366 * the result is the value closer to negative infinity. If the 1367 * arguments have the same value, the result is that same 1368 * value. If either value is NaN, then the result is NaN. Unlike 1369 * the numerical comparison operators, this method considers 1370 * negative zero to be strictly smaller than positive zero. If 1371 * one argument is positive zero and the other is negative zero, 1372 * the result is negative zero. 1373 * 1374 * @param a an argument. 1375 * @param b another argument. 1376 * @return the smaller of {@code a} and {@code b}. 1377 */ 1378 public static float min(float a, float b) { 1379 if (a != a) 1380 return a; // a is NaN 1381 if ((a == 0.0f) && 1382 (b == 0.0f) && 1383 (Float.floatToRawIntBits(b) == negativeZeroFloatBits)) { 1384 // Raw conversion ok since NaN can't map to -0.0. 1385 return b; 1386 } 1387 return (a <= b) ? a : b; 1388 } 1389 1390 /** 1391 * Returns the smaller of two {@code double} values. That 1392 * is, the result is the value closer to negative infinity. If the 1393 * arguments have the same value, the result is that same 1394 * value. If either value is NaN, then the result is NaN. Unlike 1395 * the numerical comparison operators, this method considers 1396 * negative zero to be strictly smaller than positive zero. If one 1397 * argument is positive zero and the other is negative zero, the 1398 * result is negative zero. 1399 * 1400 * @param a an argument. 1401 * @param b another argument. 1402 * @return the smaller of {@code a} and {@code b}. 1403 */ 1404 public static double min(double a, double b) { 1405 if (a != a) 1406 return a; // a is NaN 1407 if ((a == 0.0d) && 1408 (b == 0.0d) && 1409 (Double.doubleToRawLongBits(b) == negativeZeroDoubleBits)) { 1410 // Raw conversion ok since NaN can't map to -0.0. 1411 return b; 1412 } 1413 return (a <= b) ? a : b; 1414 } 1415 1416 /** 1417 * Returns the size of an ulp of the argument. An ulp, unit in 1418 * the last place, of a {@code double} value is the positive 1419 * distance between this floating-point value and the {@code 1420 * double} value next larger in magnitude. Note that for non-NaN 1421 * <i>x</i>, <code>ulp(-<i>x</i>) == ulp(<i>x</i>)</code>. 1422 * 1423 * <p>Special Cases: 1424 * <ul> 1425 * <li> If the argument is NaN, then the result is NaN. 1426 * <li> If the argument is positive or negative infinity, then the 1427 * result is positive infinity. 1428 * <li> If the argument is positive or negative zero, then the result is 1429 * {@code Double.MIN_VALUE}. 1430 * <li> If the argument is ±{@code Double.MAX_VALUE}, then 1431 * the result is equal to 2<sup>971</sup>. 1432 * </ul> 1433 * 1434 * @param d the floating-point value whose ulp is to be returned 1435 * @return the size of an ulp of the argument 1436 * @author Joseph D. Darcy 1437 * @since 1.5 1438 */ 1439 public static double ulp(double d) { 1440 int exp = getExponent(d); 1441 1442 switch(exp) { 1443 case DoubleConsts.MAX_EXPONENT+1: // NaN or infinity 1444 return Math.abs(d); 1445 1446 case DoubleConsts.MIN_EXPONENT-1: // zero or subnormal 1447 return Double.MIN_VALUE; 1448 1449 default: 1450 assert exp <= DoubleConsts.MAX_EXPONENT && exp >= DoubleConsts.MIN_EXPONENT; 1451 1452 // ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x)) 1453 exp = exp - (DoubleConsts.SIGNIFICAND_WIDTH-1); 1454 if (exp >= DoubleConsts.MIN_EXPONENT) { 1455 return powerOfTwoD(exp); 1456 } 1457 else { 1458 // return a subnormal result; left shift integer 1459 // representation of Double.MIN_VALUE appropriate 1460 // number of positions 1461 return Double.longBitsToDouble(1L << 1462 (exp - (DoubleConsts.MIN_EXPONENT - (DoubleConsts.SIGNIFICAND_WIDTH-1)) )); 1463 } 1464 } 1465 } 1466 1467 /** 1468 * Returns the size of an ulp of the argument. An ulp, unit in 1469 * the last place, of a {@code float} value is the positive 1470 * distance between this floating-point value and the {@code 1471 * float} value next larger in magnitude. Note that for non-NaN 1472 * <i>x</i>, <code>ulp(-<i>x</i>) == ulp(<i>x</i>)</code>. 1473 * 1474 * <p>Special Cases: 1475 * <ul> 1476 * <li> If the argument is NaN, then the result is NaN. 1477 * <li> If the argument is positive or negative infinity, then the 1478 * result is positive infinity. 1479 * <li> If the argument is positive or negative zero, then the result is 1480 * {@code Float.MIN_VALUE}. 1481 * <li> If the argument is ±{@code Float.MAX_VALUE}, then 1482 * the result is equal to 2<sup>104</sup>. 1483 * </ul> 1484 * 1485 * @param f the floating-point value whose ulp is to be returned 1486 * @return the size of an ulp of the argument 1487 * @author Joseph D. Darcy 1488 * @since 1.5 1489 */ 1490 public static float ulp(float f) { 1491 int exp = getExponent(f); 1492 1493 switch(exp) { 1494 case FloatConsts.MAX_EXPONENT+1: // NaN or infinity 1495 return Math.abs(f); 1496 1497 case FloatConsts.MIN_EXPONENT-1: // zero or subnormal 1498 return FloatConsts.MIN_VALUE; 1499 1500 default: 1501 assert exp <= FloatConsts.MAX_EXPONENT && exp >= FloatConsts.MIN_EXPONENT; 1502 1503 // ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x)) 1504 exp = exp - (FloatConsts.SIGNIFICAND_WIDTH-1); 1505 if (exp >= FloatConsts.MIN_EXPONENT) { 1506 return powerOfTwoF(exp); 1507 } 1508 else { 1509 // return a subnormal result; left shift integer 1510 // representation of FloatConsts.MIN_VALUE appropriate 1511 // number of positions 1512 return Float.intBitsToFloat(1 << 1513 (exp - (FloatConsts.MIN_EXPONENT - (FloatConsts.SIGNIFICAND_WIDTH-1)) )); 1514 } 1515 } 1516 } 1517 1518 /** 1519 * Returns the signum function of the argument; zero if the argument 1520 * is zero, 1.0 if the argument is greater than zero, -1.0 if the 1521 * argument is less than zero. 1522 * 1523 * <p>Special Cases: 1524 * <ul> 1525 * <li> If the argument is NaN, then the result is NaN. 1526 * <li> If the argument is positive zero or negative zero, then the 1527 * result is the same as the argument. 1528 * </ul> 1529 * 1530 * @param d the floating-point value whose signum is to be returned 1531 * @return the signum function of the argument 1532 * @author Joseph D. Darcy 1533 * @since 1.5 1534 */ 1535 public static double signum(double d) { 1536 return (d == 0.0 || Double.isNaN(d))?d:copySign(1.0, d); 1537 } 1538 1539 /** 1540 * Returns the signum function of the argument; zero if the argument 1541 * is zero, 1.0f if the argument is greater than zero, -1.0f if the 1542 * argument is less than zero. 1543 * 1544 * <p>Special Cases: 1545 * <ul> 1546 * <li> If the argument is NaN, then the result is NaN. 1547 * <li> If the argument is positive zero or negative zero, then the 1548 * result is the same as the argument. 1549 * </ul> 1550 * 1551 * @param f the floating-point value whose signum is to be returned 1552 * @return the signum function of the argument 1553 * @author Joseph D. Darcy 1554 * @since 1.5 1555 */ 1556 public static float signum(float f) { 1557 return (f == 0.0f || Float.isNaN(f))?f:copySign(1.0f, f); 1558 } 1559 1560 /** 1561 * Returns the hyperbolic sine of a {@code double} value. 1562 * The hyperbolic sine of <i>x</i> is defined to be 1563 * (<i>e<sup>x</sup> - e<sup>-x</sup></i>)/2 1564 * where <i>e</i> is {@linkplain Math#E Euler's number}. 1565 * 1566 * <p>Special cases: 1567 * <ul> 1568 * 1569 * <li>If the argument is NaN, then the result is NaN. 1570 * 1571 * <li>If the argument is infinite, then the result is an infinity 1572 * with the same sign as the argument. 1573 * 1574 * <li>If the argument is zero, then the result is a zero with the 1575 * same sign as the argument. 1576 * 1577 * </ul> 1578 * 1579 * <p>The computed result must be within 2.5 ulps of the exact result. 1580 * 1581 * @param x The number whose hyperbolic sine is to be returned. 1582 * @return The hyperbolic sine of {@code x}. 1583 * @since 1.5 1584 */ 1585 public static double sinh(double x) { 1586 return StrictMath.sinh(x); 1587 } 1588 1589 /** 1590 * Returns the hyperbolic cosine of a {@code double} value. 1591 * The hyperbolic cosine of <i>x</i> is defined to be 1592 * (<i>e<sup>x</sup> + e<sup>-x</sup></i>)/2 1593 * where <i>e</i> is {@linkplain Math#E Euler's number}. 1594 * 1595 * <p>Special cases: 1596 * <ul> 1597 * 1598 * <li>If the argument is NaN, then the result is NaN. 1599 * 1600 * <li>If the argument is infinite, then the result is positive 1601 * infinity. 1602 * 1603 * <li>If the argument is zero, then the result is {@code 1.0}. 1604 * 1605 * </ul> 1606 * 1607 * <p>The computed result must be within 2.5 ulps of the exact result. 1608 * 1609 * @param x The number whose hyperbolic cosine is to be returned. 1610 * @return The hyperbolic cosine of {@code x}. 1611 * @since 1.5 1612 */ 1613 public static double cosh(double x) { 1614 return StrictMath.cosh(x); 1615 } 1616 1617 /** 1618 * Returns the hyperbolic tangent of a {@code double} value. 1619 * The hyperbolic tangent of <i>x</i> is defined to be 1620 * (<i>e<sup>x</sup> - e<sup>-x</sup></i>)/(<i>e<sup>x</sup> + e<sup>-x</sup></i>), 1621 * in other words, {@linkplain Math#sinh 1622 * sinh(<i>x</i>)}/{@linkplain Math#cosh cosh(<i>x</i>)}. Note 1623 * that the absolute value of the exact tanh is always less than 1624 * 1. 1625 * 1626 * <p>Special cases: 1627 * <ul> 1628 * 1629 * <li>If the argument is NaN, then the result is NaN. 1630 * 1631 * <li>If the argument is zero, then the result is a zero with the 1632 * same sign as the argument. 1633 * 1634 * <li>If the argument is positive infinity, then the result is 1635 * {@code +1.0}. 1636 * 1637 * <li>If the argument is negative infinity, then the result is 1638 * {@code -1.0}. 1639 * 1640 * </ul> 1641 * 1642 * <p>The computed result must be within 2.5 ulps of the exact result. 1643 * The result of {@code tanh} for any finite input must have 1644 * an absolute value less than or equal to 1. Note that once the 1645 * exact result of tanh is within 1/2 of an ulp of the limit value 1646 * of ±1, correctly signed ±{@code 1.0} should 1647 * be returned. 1648 * 1649 * @param x The number whose hyperbolic tangent is to be returned. 1650 * @return The hyperbolic tangent of {@code x}. 1651 * @since 1.5 1652 */ 1653 public static double tanh(double x) { 1654 return StrictMath.tanh(x); 1655 } 1656 1657 /** 1658 * Returns sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) 1659 * without intermediate overflow or underflow. 1660 * 1661 * <p>Special cases: 1662 * <ul> 1663 * 1664 * <li> If either argument is infinite, then the result 1665 * is positive infinity. 1666 * 1667 * <li> If either argument is NaN and neither argument is infinite, 1668 * then the result is NaN. 1669 * 1670 * </ul> 1671 * 1672 * <p>The computed result must be within 1 ulp of the exact 1673 * result. If one parameter is held constant, the results must be 1674 * semi-monotonic in the other parameter. 1675 * 1676 * @param x a value 1677 * @param y a value 1678 * @return sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) 1679 * without intermediate overflow or underflow 1680 * @since 1.5 1681 */ 1682 public static double hypot(double x, double y) { 1683 return StrictMath.hypot(x, y); 1684 } 1685 1686 /** 1687 * Returns <i>e</i><sup>x</sup> -1. Note that for values of 1688 * <i>x</i> near 0, the exact sum of 1689 * {@code expm1(x)} + 1 is much closer to the true 1690 * result of <i>e</i><sup>x</sup> than {@code exp(x)}. 1691 * 1692 * <p>Special cases: 1693 * <ul> 1694 * <li>If the argument is NaN, the result is NaN. 1695 * 1696 * <li>If the argument is positive infinity, then the result is 1697 * positive infinity. 1698 * 1699 * <li>If the argument is negative infinity, then the result is 1700 * -1.0. 1701 * 1702 * <li>If the argument is zero, then the result is a zero with the 1703 * same sign as the argument. 1704 * 1705 * </ul> 1706 * 1707 * <p>The computed result must be within 1 ulp of the exact result. 1708 * Results must be semi-monotonic. The result of 1709 * {@code expm1} for any finite input must be greater than or 1710 * equal to {@code -1.0}. Note that once the exact result of 1711 * <i>e</i><sup>{@code x}</sup> - 1 is within 1/2 1712 * ulp of the limit value -1, {@code -1.0} should be 1713 * returned. 1714 * 1715 * @param x the exponent to raise <i>e</i> to in the computation of 1716 * <i>e</i><sup>{@code x}</sup> -1. 1717 * @return the value <i>e</i><sup>{@code x}</sup> - 1. 1718 * @since 1.5 1719 */ 1720 public static double expm1(double x) { 1721 return StrictMath.expm1(x); 1722 } 1723 1724 /** 1725 * Returns the natural logarithm of the sum of the argument and 1. 1726 * Note that for small values {@code x}, the result of 1727 * {@code log1p(x)} is much closer to the true result of ln(1 1728 * + {@code x}) than the floating-point evaluation of 1729 * {@code log(1.0+x)}. 1730 * 1731 * <p>Special cases: 1732 * 1733 * <ul> 1734 * 1735 * <li>If the argument is NaN or less than -1, then the result is 1736 * NaN. 1737 * 1738 * <li>If the argument is positive infinity, then the result is 1739 * positive infinity. 1740 * 1741 * <li>If the argument is negative one, then the result is 1742 * negative infinity. 1743 * 1744 * <li>If the argument is zero, then the result is a zero with the 1745 * same sign as the argument. 1746 * 1747 * </ul> 1748 * 1749 * <p>The computed result must be within 1 ulp of the exact result. 1750 * Results must be semi-monotonic. 1751 * 1752 * @param x a value 1753 * @return the value ln({@code x} + 1), the natural 1754 * log of {@code x} + 1 1755 * @since 1.5 1756 */ 1757 public static double log1p(double x) { 1758 return StrictMath.log1p(x); 1759 } 1760 1761 /** 1762 * Returns the first floating-point argument with the sign of the 1763 * second floating-point argument. Note that unlike the {@link 1764 * StrictMath#copySign(double, double) StrictMath.copySign} 1765 * method, this method does not require NaN {@code sign} 1766 * arguments to be treated as positive values; implementations are 1767 * permitted to treat some NaN arguments as positive and other NaN 1768 * arguments as negative to allow greater performance. 1769 * 1770 * @param magnitude the parameter providing the magnitude of the result 1771 * @param sign the parameter providing the sign of the result 1772 * @return a value with the magnitude of {@code magnitude} 1773 * and the sign of {@code sign}. 1774 * @since 1.6 1775 */ 1776 public static double copySign(double magnitude, double sign) { 1777 return Double.longBitsToDouble((Double.doubleToRawLongBits(sign) & 1778 (DoubleConsts.SIGN_BIT_MASK)) | 1779 (Double.doubleToRawLongBits(magnitude) & 1780 (DoubleConsts.EXP_BIT_MASK | 1781 DoubleConsts.SIGNIF_BIT_MASK))); 1782 } 1783 1784 /** 1785 * Returns the first floating-point argument with the sign of the 1786 * second floating-point argument. Note that unlike the {@link 1787 * StrictMath#copySign(float, float) StrictMath.copySign} 1788 * method, this method does not require NaN {@code sign} 1789 * arguments to be treated as positive values; implementations are 1790 * permitted to treat some NaN arguments as positive and other NaN 1791 * arguments as negative to allow greater performance. 1792 * 1793 * @param magnitude the parameter providing the magnitude of the result 1794 * @param sign the parameter providing the sign of the result 1795 * @return a value with the magnitude of {@code magnitude} 1796 * and the sign of {@code sign}. 1797 * @since 1.6 1798 */ 1799 public static float copySign(float magnitude, float sign) { 1800 return Float.intBitsToFloat((Float.floatToRawIntBits(sign) & 1801 (FloatConsts.SIGN_BIT_MASK)) | 1802 (Float.floatToRawIntBits(magnitude) & 1803 (FloatConsts.EXP_BIT_MASK | 1804 FloatConsts.SIGNIF_BIT_MASK))); 1805 } 1806 1807 /** 1808 * Returns the unbiased exponent used in the representation of a 1809 * {@code float}. Special cases: 1810 * 1811 * <ul> 1812 * <li>If the argument is NaN or infinite, then the result is 1813 * {@link Float#MAX_EXPONENT} + 1. 1814 * <li>If the argument is zero or subnormal, then the result is 1815 * {@link Float#MIN_EXPONENT} -1. 1816 * </ul> 1817 * @param f a {@code float} value 1818 * @return the unbiased exponent of the argument 1819 * @since 1.6 1820 */ 1821 public static int getExponent(float f) { 1822 /* 1823 * Bitwise convert f to integer, mask out exponent bits, shift 1824 * to the right and then subtract out float's bias adjust to 1825 * get true exponent value 1826 */ 1827 return ((Float.floatToRawIntBits(f) & FloatConsts.EXP_BIT_MASK) >> 1828 (FloatConsts.SIGNIFICAND_WIDTH - 1)) - FloatConsts.EXP_BIAS; 1829 } 1830 1831 /** 1832 * Returns the unbiased exponent used in the representation of a 1833 * {@code double}. Special cases: 1834 * 1835 * <ul> 1836 * <li>If the argument is NaN or infinite, then the result is 1837 * {@link Double#MAX_EXPONENT} + 1. 1838 * <li>If the argument is zero or subnormal, then the result is 1839 * {@link Double#MIN_EXPONENT} -1. 1840 * </ul> 1841 * @param d a {@code double} value 1842 * @return the unbiased exponent of the argument 1843 * @since 1.6 1844 */ 1845 public static int getExponent(double d) { 1846 /* 1847 * Bitwise convert d to long, mask out exponent bits, shift 1848 * to the right and then subtract out double's bias adjust to 1849 * get true exponent value. 1850 */ 1851 return (int)(((Double.doubleToRawLongBits(d) & DoubleConsts.EXP_BIT_MASK) >> 1852 (DoubleConsts.SIGNIFICAND_WIDTH - 1)) - DoubleConsts.EXP_BIAS); 1853 } 1854 1855 /** 1856 * Returns the floating-point number adjacent to the first 1857 * argument in the direction of the second argument. If both 1858 * arguments compare as equal the second argument is returned. 1859 * 1860 * <p> 1861 * Special cases: 1862 * <ul> 1863 * <li> If either argument is a NaN, then NaN is returned. 1864 * 1865 * <li> If both arguments are signed zeros, {@code direction} 1866 * is returned unchanged (as implied by the requirement of 1867 * returning the second argument if the arguments compare as 1868 * equal). 1869 * 1870 * <li> If {@code start} is 1871 * ±{@link Double#MIN_VALUE} and {@code direction} 1872 * has a value such that the result should have a smaller 1873 * magnitude, then a zero with the same sign as {@code start} 1874 * is returned. 1875 * 1876 * <li> If {@code start} is infinite and 1877 * {@code direction} has a value such that the result should 1878 * have a smaller magnitude, {@link Double#MAX_VALUE} with the 1879 * same sign as {@code start} is returned. 1880 * 1881 * <li> If {@code start} is equal to ± 1882 * {@link Double#MAX_VALUE} and {@code direction} has a 1883 * value such that the result should have a larger magnitude, an 1884 * infinity with same sign as {@code start} is returned. 1885 * </ul> 1886 * 1887 * @param start starting floating-point value 1888 * @param direction value indicating which of 1889 * {@code start}'s neighbors or {@code start} should 1890 * be returned 1891 * @return The floating-point number adjacent to {@code start} in the 1892 * direction of {@code direction}. 1893 * @since 1.6 1894 */ 1895 public static double nextAfter(double start, double direction) { 1896 /* 1897 * The cases: 1898 * 1899 * nextAfter(+infinity, 0) == MAX_VALUE 1900 * nextAfter(+infinity, +infinity) == +infinity 1901 * nextAfter(-infinity, 0) == -MAX_VALUE 1902 * nextAfter(-infinity, -infinity) == -infinity 1903 * 1904 * are naturally handled without any additional testing 1905 */ 1906 1907 /* 1908 * IEEE 754 floating-point numbers are lexicographically 1909 * ordered if treated as signed-magnitude integers. 1910 * Since Java's integers are two's complement, 1911 * incrementing the two's complement representation of a 1912 * logically negative floating-point value *decrements* 1913 * the signed-magnitude representation. Therefore, when 1914 * the integer representation of a floating-point value 1915 * is negative, the adjustment to the representation is in 1916 * the opposite direction from what would initially be expected. 1917 */ 1918 1919 // Branch to descending case first as it is more costly than ascending 1920 // case due to start != 0.0d conditional. 1921 if (start > direction) { // descending 1922 if (start != 0.0d) { 1923 final long transducer = Double.doubleToRawLongBits(start); 1924 return Double.longBitsToDouble(transducer + ((transducer > 0L) ? -1L : 1L)); 1925 } else { // start == 0.0d && direction < 0.0d 1926 return -Double.MIN_VALUE; 1927 } 1928 } else if (start < direction) { // ascending 1929 // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0) 1930 // then bitwise convert start to integer. 1931 final long transducer = Double.doubleToRawLongBits(start + 0.0d); 1932 return Double.longBitsToDouble(transducer + ((transducer >= 0L) ? 1L : -1L)); 1933 } else if (start == direction) { 1934 return direction; 1935 } else { // isNaN(start) || isNaN(direction) 1936 return start + direction; 1937 } 1938 } 1939 1940 /** 1941 * Returns the floating-point number adjacent to the first 1942 * argument in the direction of the second argument. If both 1943 * arguments compare as equal a value equivalent to the second argument 1944 * is returned. 1945 * 1946 * <p> 1947 * Special cases: 1948 * <ul> 1949 * <li> If either argument is a NaN, then NaN is returned. 1950 * 1951 * <li> If both arguments are signed zeros, a value equivalent 1952 * to {@code direction} is returned. 1953 * 1954 * <li> If {@code start} is 1955 * ±{@link Float#MIN_VALUE} and {@code direction} 1956 * has a value such that the result should have a smaller 1957 * magnitude, then a zero with the same sign as {@code start} 1958 * is returned. 1959 * 1960 * <li> If {@code start} is infinite and 1961 * {@code direction} has a value such that the result should 1962 * have a smaller magnitude, {@link Float#MAX_VALUE} with the 1963 * same sign as {@code start} is returned. 1964 * 1965 * <li> If {@code start} is equal to ± 1966 * {@link Float#MAX_VALUE} and {@code direction} has a 1967 * value such that the result should have a larger magnitude, an 1968 * infinity with same sign as {@code start} is returned. 1969 * </ul> 1970 * 1971 * @param start starting floating-point value 1972 * @param direction value indicating which of 1973 * {@code start}'s neighbors or {@code start} should 1974 * be returned 1975 * @return The floating-point number adjacent to {@code start} in the 1976 * direction of {@code direction}. 1977 * @since 1.6 1978 */ 1979 public static float nextAfter(float start, double direction) { 1980 /* 1981 * The cases: 1982 * 1983 * nextAfter(+infinity, 0) == MAX_VALUE 1984 * nextAfter(+infinity, +infinity) == +infinity 1985 * nextAfter(-infinity, 0) == -MAX_VALUE 1986 * nextAfter(-infinity, -infinity) == -infinity 1987 * 1988 * are naturally handled without any additional testing 1989 */ 1990 1991 /* 1992 * IEEE 754 floating-point numbers are lexicographically 1993 * ordered if treated as signed-magnitude integers. 1994 * Since Java's integers are two's complement, 1995 * incrementing the two's complement representation of a 1996 * logically negative floating-point value *decrements* 1997 * the signed-magnitude representation. Therefore, when 1998 * the integer representation of a floating-point value 1999 * is negative, the adjustment to the representation is in 2000 * the opposite direction from what would initially be expected. 2001 */ 2002 2003 // Branch to descending case first as it is more costly than ascending 2004 // case due to start != 0.0f conditional. 2005 if (start > direction) { // descending 2006 if (start != 0.0f) { 2007 final int transducer = Float.floatToRawIntBits(start); 2008 return Float.intBitsToFloat(transducer + ((transducer > 0) ? -1 : 1)); 2009 } else { // start == 0.0f && direction < 0.0f 2010 return -Float.MIN_VALUE; 2011 } 2012 } else if (start < direction) { // ascending 2013 // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0) 2014 // then bitwise convert start to integer. 2015 final int transducer = Float.floatToRawIntBits(start + 0.0f); 2016 return Float.intBitsToFloat(transducer + ((transducer >= 0) ? 1 : -1)); 2017 } else if (start == direction) { 2018 return (float)direction; 2019 } else { // isNaN(start) || isNaN(direction) 2020 return start + (float)direction; 2021 } 2022 } 2023 2024 /** 2025 * Returns the floating-point value adjacent to {@code d} in 2026 * the direction of positive infinity. This method is 2027 * semantically equivalent to {@code nextAfter(d, 2028 * Double.POSITIVE_INFINITY)}; however, a {@code nextUp} 2029 * implementation may run faster than its equivalent 2030 * {@code nextAfter} call. 2031 * 2032 * <p>Special Cases: 2033 * <ul> 2034 * <li> If the argument is NaN, the result is NaN. 2035 * 2036 * <li> If the argument is positive infinity, the result is 2037 * positive infinity. 2038 * 2039 * <li> If the argument is zero, the result is 2040 * {@link Double#MIN_VALUE} 2041 * 2042 * </ul> 2043 * 2044 * @param d starting floating-point value 2045 * @return The adjacent floating-point value closer to positive 2046 * infinity. 2047 * @since 1.6 2048 */ 2049 public static double nextUp(double d) { 2050 // Use a single conditional and handle the likely cases first. 2051 if (d < Double.POSITIVE_INFINITY) { 2052 // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0). 2053 final long transducer = Double.doubleToRawLongBits(d + 0.0D); 2054 return Double.longBitsToDouble(transducer + ((transducer >= 0L) ? 1L : -1L)); 2055 } else { // d is NaN or +Infinity 2056 return d; 2057 } 2058 } 2059 2060 /** 2061 * Returns the floating-point value adjacent to {@code f} in 2062 * the direction of positive infinity. This method is 2063 * semantically equivalent to {@code nextAfter(f, 2064 * Float.POSITIVE_INFINITY)}; however, a {@code nextUp} 2065 * implementation may run faster than its equivalent 2066 * {@code nextAfter} call. 2067 * 2068 * <p>Special Cases: 2069 * <ul> 2070 * <li> If the argument is NaN, the result is NaN. 2071 * 2072 * <li> If the argument is positive infinity, the result is 2073 * positive infinity. 2074 * 2075 * <li> If the argument is zero, the result is 2076 * {@link Float#MIN_VALUE} 2077 * 2078 * </ul> 2079 * 2080 * @param f starting floating-point value 2081 * @return The adjacent floating-point value closer to positive 2082 * infinity. 2083 * @since 1.6 2084 */ 2085 public static float nextUp(float f) { 2086 // Use a single conditional and handle the likely cases first. 2087 if (f < Float.POSITIVE_INFINITY) { 2088 // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0). 2089 final int transducer = Float.floatToRawIntBits(f + 0.0F); 2090 return Float.intBitsToFloat(transducer + ((transducer >= 0) ? 1 : -1)); 2091 } else { // f is NaN or +Infinity 2092 return f; 2093 } 2094 } 2095 2096 /** 2097 * Returns the floating-point value adjacent to {@code d} in 2098 * the direction of negative infinity. This method is 2099 * semantically equivalent to {@code nextAfter(d, 2100 * Double.NEGATIVE_INFINITY)}; however, a 2101 * {@code nextDown} implementation may run faster than its 2102 * equivalent {@code nextAfter} call. 2103 * 2104 * <p>Special Cases: 2105 * <ul> 2106 * <li> If the argument is NaN, the result is NaN. 2107 * 2108 * <li> If the argument is negative infinity, the result is 2109 * negative infinity. 2110 * 2111 * <li> If the argument is zero, the result is 2112 * {@code -Double.MIN_VALUE} 2113 * 2114 * </ul> 2115 * 2116 * @param d starting floating-point value 2117 * @return The adjacent floating-point value closer to negative 2118 * infinity. 2119 * @since 1.8 2120 */ 2121 public static double nextDown(double d) { 2122 if (Double.isNaN(d) || d == Double.NEGATIVE_INFINITY) 2123 return d; 2124 else { 2125 if (d == 0.0) 2126 return -Double.MIN_VALUE; 2127 else 2128 return Double.longBitsToDouble(Double.doubleToRawLongBits(d) + 2129 ((d > 0.0d)?-1L:+1L)); 2130 } 2131 } 2132 2133 /** 2134 * Returns the floating-point value adjacent to {@code f} in 2135 * the direction of negative infinity. This method is 2136 * semantically equivalent to {@code nextAfter(f, 2137 * Float.NEGATIVE_INFINITY)}; however, a 2138 * {@code nextDown} implementation may run faster than its 2139 * equivalent {@code nextAfter} call. 2140 * 2141 * <p>Special Cases: 2142 * <ul> 2143 * <li> If the argument is NaN, the result is NaN. 2144 * 2145 * <li> If the argument is negative infinity, the result is 2146 * negative infinity. 2147 * 2148 * <li> If the argument is zero, the result is 2149 * {@code -Float.MIN_VALUE} 2150 * 2151 * </ul> 2152 * 2153 * @param f starting floating-point value 2154 * @return The adjacent floating-point value closer to negative 2155 * infinity. 2156 * @since 1.8 2157 */ 2158 public static float nextDown(float f) { 2159 if (Float.isNaN(f) || f == Float.NEGATIVE_INFINITY) 2160 return f; 2161 else { 2162 if (f == 0.0f) 2163 return -Float.MIN_VALUE; 2164 else 2165 return Float.intBitsToFloat(Float.floatToRawIntBits(f) + 2166 ((f > 0.0f)?-1:+1)); 2167 } 2168 } 2169 2170 /** 2171 * Returns {@code d} × 2172 * 2<sup>{@code scaleFactor}</sup> rounded as if performed 2173 * by a single correctly rounded floating-point multiply to a 2174 * member of the double value set. See the Java 2175 * Language Specification for a discussion of floating-point 2176 * value sets. If the exponent of the result is between {@link 2177 * Double#MIN_EXPONENT} and {@link Double#MAX_EXPONENT}, the 2178 * answer is calculated exactly. If the exponent of the result 2179 * would be larger than {@code Double.MAX_EXPONENT}, an 2180 * infinity is returned. Note that if the result is subnormal, 2181 * precision may be lost; that is, when {@code scalb(x, n)} 2182 * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal 2183 * <i>x</i>. When the result is non-NaN, the result has the same 2184 * sign as {@code d}. 2185 * 2186 * <p>Special cases: 2187 * <ul> 2188 * <li> If the first argument is NaN, NaN is returned. 2189 * <li> If the first argument is infinite, then an infinity of the 2190 * same sign is returned. 2191 * <li> If the first argument is zero, then a zero of the same 2192 * sign is returned. 2193 * </ul> 2194 * 2195 * @param d number to be scaled by a power of two. 2196 * @param scaleFactor power of 2 used to scale {@code d} 2197 * @return {@code d} × 2<sup>{@code scaleFactor}</sup> 2198 * @since 1.6 2199 */ 2200 public static double scalb(double d, int scaleFactor) { 2201 /* 2202 * This method does not need to be declared strictfp to 2203 * compute the same correct result on all platforms. When 2204 * scaling up, it does not matter what order the 2205 * multiply-store operations are done; the result will be 2206 * finite or overflow regardless of the operation ordering. 2207 * However, to get the correct result when scaling down, a 2208 * particular ordering must be used. 2209 * 2210 * When scaling down, the multiply-store operations are 2211 * sequenced so that it is not possible for two consecutive 2212 * multiply-stores to return subnormal results. If one 2213 * multiply-store result is subnormal, the next multiply will 2214 * round it away to zero. This is done by first multiplying 2215 * by 2 ^ (scaleFactor % n) and then multiplying several 2216 * times by by 2^n as needed where n is the exponent of number 2217 * that is a covenient power of two. In this way, at most one 2218 * real rounding error occurs. If the double value set is 2219 * being used exclusively, the rounding will occur on a 2220 * multiply. If the double-extended-exponent value set is 2221 * being used, the products will (perhaps) be exact but the 2222 * stores to d are guaranteed to round to the double value 2223 * set. 2224 * 2225 * It is _not_ a valid implementation to first multiply d by 2226 * 2^MIN_EXPONENT and then by 2 ^ (scaleFactor % 2227 * MIN_EXPONENT) since even in a strictfp program double 2228 * rounding on underflow could occur; e.g. if the scaleFactor 2229 * argument was (MIN_EXPONENT - n) and the exponent of d was a 2230 * little less than -(MIN_EXPONENT - n), meaning the final 2231 * result would be subnormal. 2232 * 2233 * Since exact reproducibility of this method can be achieved 2234 * without any undue performance burden, there is no 2235 * compelling reason to allow double rounding on underflow in 2236 * scalb. 2237 */ 2238 2239 // magnitude of a power of two so large that scaling a finite 2240 // nonzero value by it would be guaranteed to over or 2241 // underflow; due to rounding, scaling down takes takes an 2242 // additional power of two which is reflected here 2243 final int MAX_SCALE = DoubleConsts.MAX_EXPONENT + -DoubleConsts.MIN_EXPONENT + 2244 DoubleConsts.SIGNIFICAND_WIDTH + 1; 2245 int exp_adjust = 0; 2246 int scale_increment = 0; 2247 double exp_delta = Double.NaN; 2248 2249 // Make sure scaling factor is in a reasonable range 2250 2251 if(scaleFactor < 0) { 2252 scaleFactor = Math.max(scaleFactor, -MAX_SCALE); 2253 scale_increment = -512; 2254 exp_delta = twoToTheDoubleScaleDown; 2255 } 2256 else { 2257 scaleFactor = Math.min(scaleFactor, MAX_SCALE); 2258 scale_increment = 512; 2259 exp_delta = twoToTheDoubleScaleUp; 2260 } 2261 2262 // Calculate (scaleFactor % +/-512), 512 = 2^9, using 2263 // technique from "Hacker's Delight" section 10-2. 2264 int t = (scaleFactor >> 9-1) >>> 32 - 9; 2265 exp_adjust = ((scaleFactor + t) & (512 -1)) - t; 2266 2267 d *= powerOfTwoD(exp_adjust); 2268 scaleFactor -= exp_adjust; 2269 2270 while(scaleFactor != 0) { 2271 d *= exp_delta; 2272 scaleFactor -= scale_increment; 2273 } 2274 return d; 2275 } 2276 2277 /** 2278 * Returns {@code f} × 2279 * 2<sup>{@code scaleFactor}</sup> rounded as if performed 2280 * by a single correctly rounded floating-point multiply to a 2281 * member of the float value set. See the Java 2282 * Language Specification for a discussion of floating-point 2283 * value sets. If the exponent of the result is between {@link 2284 * Float#MIN_EXPONENT} and {@link Float#MAX_EXPONENT}, the 2285 * answer is calculated exactly. If the exponent of the result 2286 * would be larger than {@code Float.MAX_EXPONENT}, an 2287 * infinity is returned. Note that if the result is subnormal, 2288 * precision may be lost; that is, when {@code scalb(x, n)} 2289 * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal 2290 * <i>x</i>. When the result is non-NaN, the result has the same 2291 * sign as {@code f}. 2292 * 2293 * <p>Special cases: 2294 * <ul> 2295 * <li> If the first argument is NaN, NaN is returned. 2296 * <li> If the first argument is infinite, then an infinity of the 2297 * same sign is returned. 2298 * <li> If the first argument is zero, then a zero of the same 2299 * sign is returned. 2300 * </ul> 2301 * 2302 * @param f number to be scaled by a power of two. 2303 * @param scaleFactor power of 2 used to scale {@code f} 2304 * @return {@code f} × 2<sup>{@code scaleFactor}</sup> 2305 * @since 1.6 2306 */ 2307 public static float scalb(float f, int scaleFactor) { 2308 // magnitude of a power of two so large that scaling a finite 2309 // nonzero value by it would be guaranteed to over or 2310 // underflow; due to rounding, scaling down takes takes an 2311 // additional power of two which is reflected here 2312 final int MAX_SCALE = FloatConsts.MAX_EXPONENT + -FloatConsts.MIN_EXPONENT + 2313 FloatConsts.SIGNIFICAND_WIDTH + 1; 2314 2315 // Make sure scaling factor is in a reasonable range 2316 scaleFactor = Math.max(Math.min(scaleFactor, MAX_SCALE), -MAX_SCALE); 2317 2318 /* 2319 * Since + MAX_SCALE for float fits well within the double 2320 * exponent range and + float -> double conversion is exact 2321 * the multiplication below will be exact. Therefore, the 2322 * rounding that occurs when the double product is cast to 2323 * float will be the correctly rounded float result. Since 2324 * all operations other than the final multiply will be exact, 2325 * it is not necessary to declare this method strictfp. 2326 */ 2327 return (float)((double)f*powerOfTwoD(scaleFactor)); 2328 } 2329 2330 // Constants used in scalb 2331 static double twoToTheDoubleScaleUp = powerOfTwoD(512); 2332 static double twoToTheDoubleScaleDown = powerOfTwoD(-512); 2333 2334 /** 2335 * Returns a floating-point power of two in the normal range. 2336 */ 2337 static double powerOfTwoD(int n) { 2338 assert(n >= DoubleConsts.MIN_EXPONENT && n <= DoubleConsts.MAX_EXPONENT); 2339 return Double.longBitsToDouble((((long)n + (long)DoubleConsts.EXP_BIAS) << 2340 (DoubleConsts.SIGNIFICAND_WIDTH-1)) 2341 & DoubleConsts.EXP_BIT_MASK); 2342 } 2343 2344 /** 2345 * Returns a floating-point power of two in the normal range. 2346 */ 2347 static float powerOfTwoF(int n) { 2348 assert(n >= FloatConsts.MIN_EXPONENT && n <= FloatConsts.MAX_EXPONENT); 2349 return Float.intBitsToFloat(((n + FloatConsts.EXP_BIAS) << 2350 (FloatConsts.SIGNIFICAND_WIDTH-1)) 2351 & FloatConsts.EXP_BIT_MASK); 2352 } 2353 }