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 * @return a pseudorandom {@code double} greater than or equal 769 * to {@code 0.0} and less than {@code 1.0}. 770 * @see Random#nextDouble() 771 */ 772 public static double random() { 773 return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble(); 774 } 775 776 /** 777 * Returns the sum of its arguments, 778 * throwing an exception if the result overflows an {@code int}. 779 * 780 * @param x the first value 781 * @param y the second value 782 * @return the result 783 * @throws ArithmeticException if the result overflows an int 784 * @since 1.8 785 */ 786 public static int addExact(int x, int y) { 787 int r = x + y; 788 // HD 2-12 Overflow iff both arguments have the opposite sign of the result 789 if (((x ^ r) & (y ^ r)) < 0) { 790 throw new ArithmeticException("integer overflow"); 791 } 792 return r; 793 } 794 795 /** 796 * Returns the sum of its arguments, 797 * throwing an exception if the result overflows a {@code long}. 798 * 799 * @param x the first value 800 * @param y the second value 801 * @return the result 802 * @throws ArithmeticException if the result overflows a long 803 * @since 1.8 804 */ 805 public static long addExact(long x, long y) { 806 long r = x + y; 807 // HD 2-12 Overflow iff both arguments have the opposite sign of the result 808 if (((x ^ r) & (y ^ r)) < 0) { 809 throw new ArithmeticException("long overflow"); 810 } 811 return r; 812 } 813 814 /** 815 * Returns the difference of the arguments, 816 * throwing an exception if the result overflows an {@code int}. 817 * 818 * @param x the first value 819 * @param y the second value to subtract from the first 820 * @return the result 821 * @throws ArithmeticException if the result overflows an int 822 * @since 1.8 823 */ 824 public static int subtractExact(int x, int y) { 825 int r = x - y; 826 // HD 2-12 Overflow iff the arguments have different signs and 827 // the sign of the result is different than the sign of x 828 if (((x ^ y) & (x ^ r)) < 0) { 829 throw new ArithmeticException("integer overflow"); 830 } 831 return r; 832 } 833 834 /** 835 * Returns the difference of the arguments, 836 * throwing an exception if the result overflows a {@code long}. 837 * 838 * @param x the first value 839 * @param y the second value to subtract from the first 840 * @return the result 841 * @throws ArithmeticException if the result overflows a long 842 * @since 1.8 843 */ 844 public static long subtractExact(long x, long y) { 845 long r = x - y; 846 // HD 2-12 Overflow iff the arguments have different signs and 847 // the sign of the result is different than the sign of x 848 if (((x ^ y) & (x ^ r)) < 0) { 849 throw new ArithmeticException("long overflow"); 850 } 851 return r; 852 } 853 854 /** 855 * Returns the product of the arguments, 856 * throwing an exception if the result overflows an {@code int}. 857 * 858 * @param x the first value 859 * @param y the second value 860 * @return the result 861 * @throws ArithmeticException if the result overflows an int 862 * @since 1.8 863 */ 864 public static int multiplyExact(int x, int y) { 865 long r = (long)x * (long)y; 866 if ((int)r != r) { 867 throw new ArithmeticException("integer overflow"); 868 } 869 return (int)r; 870 } 871 872 /** 873 * Returns the product of the arguments, 874 * throwing an exception if the result overflows a {@code long}. 875 * 876 * @param x the first value 877 * @param y the second value 878 * @return the result 879 * @throws ArithmeticException if the result overflows a long 880 * @since 1.8 881 */ 882 public static long multiplyExact(long x, long y) { 883 long r = x * y; 884 long ax = Math.abs(x); 885 long ay = Math.abs(y); 886 if (((ax | ay) >>> 31 != 0)) { 887 // Some bits greater than 2^31 that might cause overflow 888 // Check the result using the divide operator 889 // and check for the special case of Long.MIN_VALUE * -1 890 if (((y != 0) && (r / y != x)) || 891 (x == Long.MIN_VALUE && y == -1)) { 892 throw new ArithmeticException("long overflow"); 893 } 894 } 895 return r; 896 } 897 898 /** 899 * Returns the argument incremented by one, throwing an exception if the 900 * result overflows an {@code int}. 901 * 902 * @param a the value to increment 903 * @return the result 904 * @throws ArithmeticException if the result overflows an int 905 * @since 1.8 906 */ 907 public static int incrementExact(int a) { 908 if (a == Integer.MAX_VALUE) { 909 throw new ArithmeticException("integer overflow"); 910 } 911 912 return a + 1; 913 } 914 915 /** 916 * Returns the argument incremented by one, throwing an exception if the 917 * result overflows a {@code long}. 918 * 919 * @param a the value to increment 920 * @return the result 921 * @throws ArithmeticException if the result overflows a long 922 * @since 1.8 923 */ 924 public static long incrementExact(long a) { 925 if (a == Long.MAX_VALUE) { 926 throw new ArithmeticException("long overflow"); 927 } 928 929 return a + 1L; 930 } 931 932 /** 933 * Returns the argument decremented by one, throwing an exception if the 934 * result overflows an {@code int}. 935 * 936 * @param a the value to decrement 937 * @return the result 938 * @throws ArithmeticException if the result overflows an int 939 * @since 1.8 940 */ 941 public static int decrementExact(int a) { 942 if (a == Integer.MIN_VALUE) { 943 throw new ArithmeticException("integer overflow"); 944 } 945 946 return a - 1; 947 } 948 949 /** 950 * Returns the argument decremented by one, throwing an exception if the 951 * result overflows a {@code long}. 952 * 953 * @param a the value to decrement 954 * @return the result 955 * @throws ArithmeticException if the result overflows a long 956 * @since 1.8 957 */ 958 public static long decrementExact(long a) { 959 if (a == Long.MIN_VALUE) { 960 throw new ArithmeticException("long overflow"); 961 } 962 963 return a - 1L; 964 } 965 966 /** 967 * Returns the negation of the argument, throwing an exception if the 968 * result overflows an {@code int}. 969 * 970 * @param a the value to negate 971 * @return the result 972 * @throws ArithmeticException if the result overflows an int 973 * @since 1.8 974 */ 975 public static int negateExact(int a) { 976 if (a == Integer.MIN_VALUE) { 977 throw new ArithmeticException("integer overflow"); 978 } 979 980 return -a; 981 } 982 983 /** 984 * Returns the negation of the argument, throwing an exception if the 985 * result overflows a {@code long}. 986 * 987 * @param a the value to negate 988 * @return the result 989 * @throws ArithmeticException if the result overflows a long 990 * @since 1.8 991 */ 992 public static long negateExact(long a) { 993 if (a == Long.MIN_VALUE) { 994 throw new ArithmeticException("long overflow"); 995 } 996 997 return -a; 998 } 999 1000 /** 1001 * Returns the value of the {@code long} argument; 1002 * throwing an exception if the value overflows an {@code int}. 1003 * 1004 * @param value the long value 1005 * @return the argument as an int 1006 * @throws ArithmeticException if the {@code argument} overflows an int 1007 * @since 1.8 1008 */ 1009 public static int toIntExact(long value) { 1010 if ((int)value != value) { 1011 throw new ArithmeticException("integer overflow"); 1012 } 1013 return (int)value; 1014 } 1015 1016 /** 1017 * Returns the largest (closest to positive infinity) 1018 * {@code int} value that is less than or equal to the algebraic quotient. 1019 * There is one special case, if the dividend is the 1020 * {@linkplain Integer#MIN_VALUE Integer.MIN_VALUE} and the divisor is {@code -1}, 1021 * then integer overflow occurs and 1022 * the result is equal to the {@code Integer.MIN_VALUE}. 1023 * <p> 1024 * Normal integer division operates under the round to zero rounding mode 1025 * (truncation). This operation instead acts under the round toward 1026 * negative infinity (floor) rounding mode. 1027 * The floor rounding mode gives different results than truncation 1028 * when the exact result is negative. 1029 * <ul> 1030 * <li>If the signs of the arguments are the same, the results of 1031 * {@code floorDiv} and the {@code /} operator are the same. <br> 1032 * For example, {@code floorDiv(4, 3) == 1} and {@code (4 / 3) == 1}.</li> 1033 * <li>If the signs of the arguments are different, the quotient is negative and 1034 * {@code floorDiv} returns the integer less than or equal to the quotient 1035 * and the {@code /} operator returns the integer closest to zero.<br> 1036 * For example, {@code floorDiv(-4, 3) == -2}, 1037 * whereas {@code (-4 / 3) == -1}. 1038 * </li> 1039 * </ul> 1040 * <p> 1041 * 1042 * @param x the dividend 1043 * @param y the divisor 1044 * @return the largest (closest to positive infinity) 1045 * {@code int} value that is less than or equal to the algebraic quotient. 1046 * @throws ArithmeticException if the divisor {@code y} is zero 1047 * @see #floorMod(int, int) 1048 * @see #floor(double) 1049 * @since 1.8 1050 */ 1051 public static int floorDiv(int x, int y) { 1052 int r = x / y; 1053 // if the signs are different and modulo not zero, round down 1054 if ((x ^ y) < 0 && (r * y != x)) { 1055 r--; 1056 } 1057 return r; 1058 } 1059 1060 /** 1061 * Returns the largest (closest to positive infinity) 1062 * {@code long} value that is less than or equal to the algebraic quotient. 1063 * There is one special case, if the dividend is the 1064 * {@linkplain Long#MIN_VALUE Long.MIN_VALUE} and the divisor is {@code -1}, 1065 * then integer overflow occurs and 1066 * the result is equal to the {@code Long.MIN_VALUE}. 1067 * <p> 1068 * Normal integer division operates under the round to zero rounding mode 1069 * (truncation). This operation instead acts under the round toward 1070 * negative infinity (floor) rounding mode. 1071 * The floor rounding mode gives different results than truncation 1072 * when the exact result is negative. 1073 * <p> 1074 * For examples, see {@link #floorDiv(int, int)}. 1075 * 1076 * @param x the dividend 1077 * @param y the divisor 1078 * @return the largest (closest to positive infinity) 1079 * {@code long} value that is less than or equal to the algebraic quotient. 1080 * @throws ArithmeticException if the divisor {@code y} is zero 1081 * @see #floorMod(long, long) 1082 * @see #floor(double) 1083 * @since 1.8 1084 */ 1085 public static long floorDiv(long x, long y) { 1086 long r = x / y; 1087 // if the signs are different and modulo not zero, round down 1088 if ((x ^ y) < 0 && (r * y != x)) { 1089 r--; 1090 } 1091 return r; 1092 } 1093 1094 /** 1095 * Returns the floor modulus of the {@code int} arguments. 1096 * <p> 1097 * The floor modulus is {@code x - (floorDiv(x, y) * y)}, 1098 * has the same sign as the divisor {@code y}, and 1099 * is in the range of {@code -abs(y) < r < +abs(y)}. 1100 * 1101 * <p> 1102 * The relationship between {@code floorDiv} and {@code floorMod} is such that: 1103 * <ul> 1104 * <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x} 1105 * </ul> 1106 * <p> 1107 * The difference in values between {@code floorMod} and 1108 * the {@code %} operator is due to the difference between 1109 * {@code floorDiv} that returns the integer less than or equal to the quotient 1110 * and the {@code /} operator that returns the integer closest to zero. 1111 * <p> 1112 * Examples: 1113 * <ul> 1114 * <li>If the signs of the arguments are the same, the results 1115 * of {@code floorMod} and the {@code %} operator are the same. <br> 1116 * <ul> 1117 * <li>{@code floorMod(4, 3) == 1}; and {@code (4 % 3) == 1}</li> 1118 * </ul> 1119 * <li>If the signs of the arguments are different, the results differ from the {@code %} operator.<br> 1120 * <ul> 1121 * <li>{@code floorMod(+4, -3) == -2}; and {@code (+4 % -3) == +1} </li> 1122 * <li>{@code floorMod(-4, +3) == +2}; and {@code (-4 % +3) == -1} </li> 1123 * <li>{@code floorMod(-4, -3) == -1}; and {@code (-4 % -3) == -1 } </li> 1124 * </ul> 1125 * </li> 1126 * </ul> 1127 * <p> 1128 * If the signs of arguments are unknown and a positive modulus 1129 * is needed it can be computed as {@code (floorMod(x, y) + abs(y)) % abs(y)}. 1130 * 1131 * @param x the dividend 1132 * @param y the divisor 1133 * @return the floor modulus {@code x - (floorDiv(x, y) * y)} 1134 * @throws ArithmeticException if the divisor {@code y} is zero 1135 * @see #floorDiv(int, int) 1136 * @since 1.8 1137 */ 1138 public static int floorMod(int x, int y) { 1139 int r = x - floorDiv(x, y) * y; 1140 return r; 1141 } 1142 1143 /** 1144 * Returns the floor modulus of the {@code long} arguments. 1145 * <p> 1146 * The floor modulus is {@code x - (floorDiv(x, y) * y)}, 1147 * has the same sign as the divisor {@code y}, and 1148 * is in the range of {@code -abs(y) < r < +abs(y)}. 1149 * 1150 * <p> 1151 * The relationship between {@code floorDiv} and {@code floorMod} is such that: 1152 * <ul> 1153 * <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x} 1154 * </ul> 1155 * <p> 1156 * For examples, see {@link #floorMod(int, int)}. 1157 * 1158 * @param x the dividend 1159 * @param y the divisor 1160 * @return the floor modulus {@code x - (floorDiv(x, y) * y)} 1161 * @throws ArithmeticException if the divisor {@code y} is zero 1162 * @see #floorDiv(long, long) 1163 * @since 1.8 1164 */ 1165 public static long floorMod(long x, long y) { 1166 return x - floorDiv(x, y) * y; 1167 } 1168 1169 /** 1170 * Returns the absolute value of an {@code int} value. 1171 * If the argument is not negative, the argument is returned. 1172 * If the argument is negative, the negation of the argument is returned. 1173 * 1174 * <p>Note that if the argument is equal to the value of 1175 * {@link Integer#MIN_VALUE}, the most negative representable 1176 * {@code int} value, the result is that same value, which is 1177 * negative. 1178 * 1179 * @param a the argument whose absolute value is to be determined 1180 * @return the absolute value of the argument. 1181 */ 1182 public static int abs(int a) { 1183 return (a < 0) ? -a : a; 1184 } 1185 1186 /** 1187 * Returns the absolute value of a {@code long} value. 1188 * If the argument is not negative, the argument is returned. 1189 * If the argument is negative, the negation of the argument is returned. 1190 * 1191 * <p>Note that if the argument is equal to the value of 1192 * {@link Long#MIN_VALUE}, the most negative representable 1193 * {@code long} value, the result is that same value, which 1194 * is negative. 1195 * 1196 * @param a the argument whose absolute value is to be determined 1197 * @return the absolute value of the argument. 1198 */ 1199 public static long abs(long a) { 1200 return (a < 0) ? -a : a; 1201 } 1202 1203 /** 1204 * Returns the absolute value of a {@code float} value. 1205 * If the argument is not negative, the argument is returned. 1206 * If the argument is negative, the negation of the argument is returned. 1207 * Special cases: 1208 * <ul><li>If the argument is positive zero or negative zero, the 1209 * result is positive zero. 1210 * <li>If the argument is infinite, the result is positive infinity. 1211 * <li>If the argument is NaN, the result is NaN.</ul> 1212 * In other words, the result is the same as the value of the expression: 1213 * <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))} 1214 * 1215 * @param a the argument whose absolute value is to be determined 1216 * @return the absolute value of the argument. 1217 */ 1218 public static float abs(float a) { 1219 return (a <= 0.0F) ? 0.0F - a : a; 1220 } 1221 1222 /** 1223 * Returns the absolute value of a {@code double} value. 1224 * If the argument is not negative, the argument is returned. 1225 * If the argument is negative, the negation of the argument is returned. 1226 * Special cases: 1227 * <ul><li>If the argument is positive zero or negative zero, the result 1228 * is positive zero. 1229 * <li>If the argument is infinite, the result is positive infinity. 1230 * <li>If the argument is NaN, the result is NaN.</ul> 1231 * In other words, the result is the same as the value of the expression: 1232 * <p>{@code Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)} 1233 * 1234 * @param a the argument whose absolute value is to be determined 1235 * @return the absolute value of the argument. 1236 */ 1237 public static double abs(double a) { 1238 return (a <= 0.0D) ? 0.0D - a : a; 1239 } 1240 1241 /** 1242 * Returns the greater of two {@code int} values. That is, the 1243 * result is the argument closer to the value of 1244 * {@link Integer#MAX_VALUE}. If the arguments have the same value, 1245 * the result is that same value. 1246 * 1247 * @param a an argument. 1248 * @param b another argument. 1249 * @return the larger of {@code a} and {@code b}. 1250 */ 1251 public static int max(int a, int b) { 1252 return (a >= b) ? a : b; 1253 } 1254 1255 /** 1256 * Returns the greater of two {@code long} values. That is, the 1257 * result is the argument closer to the value of 1258 * {@link Long#MAX_VALUE}. If the arguments have the same value, 1259 * the result is that same value. 1260 * 1261 * @param a an argument. 1262 * @param b another argument. 1263 * @return the larger of {@code a} and {@code b}. 1264 */ 1265 public static long max(long a, long b) { 1266 return (a >= b) ? a : b; 1267 } 1268 1269 // Use raw bit-wise conversions on guaranteed non-NaN arguments. 1270 private static long negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f); 1271 private static long negativeZeroDoubleBits = Double.doubleToRawLongBits(-0.0d); 1272 1273 /** 1274 * Returns the greater of two {@code float} values. That is, 1275 * the result is the argument closer to positive infinity. If the 1276 * arguments have the same value, the result is that same 1277 * value. If either value is NaN, then the result is NaN. Unlike 1278 * the numerical comparison operators, this method considers 1279 * negative zero to be strictly smaller than positive zero. If one 1280 * argument is positive zero and the other negative zero, the 1281 * result is positive zero. 1282 * 1283 * @param a an argument. 1284 * @param b another argument. 1285 * @return the larger of {@code a} and {@code b}. 1286 */ 1287 public static float max(float a, float b) { 1288 if (a != a) 1289 return a; // a is NaN 1290 if ((a == 0.0f) && 1291 (b == 0.0f) && 1292 (Float.floatToRawIntBits(a) == negativeZeroFloatBits)) { 1293 // Raw conversion ok since NaN can't map to -0.0. 1294 return b; 1295 } 1296 return (a >= b) ? a : b; 1297 } 1298 1299 /** 1300 * Returns the greater of two {@code double} values. That 1301 * is, the result is the argument closer to positive infinity. If 1302 * the arguments have the same value, the result is that same 1303 * value. If either value is NaN, then the result is NaN. Unlike 1304 * the numerical comparison operators, this method considers 1305 * negative zero to be strictly smaller than positive zero. If one 1306 * argument is positive zero and the other negative zero, the 1307 * result is positive zero. 1308 * 1309 * @param a an argument. 1310 * @param b another argument. 1311 * @return the larger of {@code a} and {@code b}. 1312 */ 1313 public static double max(double a, double b) { 1314 if (a != a) 1315 return a; // a is NaN 1316 if ((a == 0.0d) && 1317 (b == 0.0d) && 1318 (Double.doubleToRawLongBits(a) == negativeZeroDoubleBits)) { 1319 // Raw conversion ok since NaN can't map to -0.0. 1320 return b; 1321 } 1322 return (a >= b) ? a : b; 1323 } 1324 1325 /** 1326 * Returns the smaller of two {@code int} values. That is, 1327 * the result the argument closer to the value of 1328 * {@link Integer#MIN_VALUE}. If the arguments have the same 1329 * value, the result is that same value. 1330 * 1331 * @param a an argument. 1332 * @param b another argument. 1333 * @return the smaller of {@code a} and {@code b}. 1334 */ 1335 public static int min(int a, int b) { 1336 return (a <= b) ? a : b; 1337 } 1338 1339 /** 1340 * Returns the smaller of two {@code long} values. That is, 1341 * the result is the argument closer to the value of 1342 * {@link Long#MIN_VALUE}. If the arguments have the same 1343 * value, the result is that same value. 1344 * 1345 * @param a an argument. 1346 * @param b another argument. 1347 * @return the smaller of {@code a} and {@code b}. 1348 */ 1349 public static long min(long a, long b) { 1350 return (a <= b) ? a : b; 1351 } 1352 1353 /** 1354 * Returns the smaller of two {@code float} values. That is, 1355 * the result is the value closer to negative infinity. If the 1356 * arguments have the same value, the result is that same 1357 * value. If either value is NaN, then the result is NaN. Unlike 1358 * the numerical comparison operators, this method considers 1359 * negative zero to be strictly smaller than positive zero. If 1360 * one argument is positive zero and the other is negative zero, 1361 * the result is negative zero. 1362 * 1363 * @param a an argument. 1364 * @param b another argument. 1365 * @return the smaller of {@code a} and {@code b}. 1366 */ 1367 public static float min(float a, float b) { 1368 if (a != a) 1369 return a; // a is NaN 1370 if ((a == 0.0f) && 1371 (b == 0.0f) && 1372 (Float.floatToRawIntBits(b) == negativeZeroFloatBits)) { 1373 // Raw conversion ok since NaN can't map to -0.0. 1374 return b; 1375 } 1376 return (a <= b) ? a : b; 1377 } 1378 1379 /** 1380 * Returns the smaller of two {@code double} values. That 1381 * is, the result is the value closer to negative infinity. If the 1382 * arguments have the same value, the result is that same 1383 * value. If either value is NaN, then the result is NaN. Unlike 1384 * the numerical comparison operators, this method considers 1385 * negative zero to be strictly smaller than positive zero. If one 1386 * argument is positive zero and the other is negative zero, the 1387 * result is negative zero. 1388 * 1389 * @param a an argument. 1390 * @param b another argument. 1391 * @return the smaller of {@code a} and {@code b}. 1392 */ 1393 public static double min(double a, double b) { 1394 if (a != a) 1395 return a; // a is NaN 1396 if ((a == 0.0d) && 1397 (b == 0.0d) && 1398 (Double.doubleToRawLongBits(b) == negativeZeroDoubleBits)) { 1399 // Raw conversion ok since NaN can't map to -0.0. 1400 return b; 1401 } 1402 return (a <= b) ? a : b; 1403 } 1404 1405 /** 1406 * Returns the size of an ulp of the argument. An ulp, unit in 1407 * the last place, of a {@code double} value is the positive 1408 * distance between this floating-point value and the {@code 1409 * double} value next larger in magnitude. Note that for non-NaN 1410 * <i>x</i>, <code>ulp(-<i>x</i>) == ulp(<i>x</i>)</code>. 1411 * 1412 * <p>Special Cases: 1413 * <ul> 1414 * <li> If the argument is NaN, then the result is NaN. 1415 * <li> If the argument is positive or negative infinity, then the 1416 * result is positive infinity. 1417 * <li> If the argument is positive or negative zero, then the result is 1418 * {@code Double.MIN_VALUE}. 1419 * <li> If the argument is ±{@code Double.MAX_VALUE}, then 1420 * the result is equal to 2<sup>971</sup>. 1421 * </ul> 1422 * 1423 * @param d the floating-point value whose ulp is to be returned 1424 * @return the size of an ulp of the argument 1425 * @author Joseph D. Darcy 1426 * @since 1.5 1427 */ 1428 public static double ulp(double d) { 1429 int exp = getExponent(d); 1430 1431 switch(exp) { 1432 case DoubleConsts.MAX_EXPONENT+1: // NaN or infinity 1433 return Math.abs(d); 1434 1435 case DoubleConsts.MIN_EXPONENT-1: // zero or subnormal 1436 return Double.MIN_VALUE; 1437 1438 default: 1439 assert exp <= DoubleConsts.MAX_EXPONENT && exp >= DoubleConsts.MIN_EXPONENT; 1440 1441 // ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x)) 1442 exp = exp - (DoubleConsts.SIGNIFICAND_WIDTH-1); 1443 if (exp >= DoubleConsts.MIN_EXPONENT) { 1444 return powerOfTwoD(exp); 1445 } 1446 else { 1447 // return a subnormal result; left shift integer 1448 // representation of Double.MIN_VALUE appropriate 1449 // number of positions 1450 return Double.longBitsToDouble(1L << 1451 (exp - (DoubleConsts.MIN_EXPONENT - (DoubleConsts.SIGNIFICAND_WIDTH-1)) )); 1452 } 1453 } 1454 } 1455 1456 /** 1457 * Returns the size of an ulp of the argument. An ulp, unit in 1458 * the last place, of a {@code float} value is the positive 1459 * distance between this floating-point value and the {@code 1460 * float} value next larger in magnitude. Note that for non-NaN 1461 * <i>x</i>, <code>ulp(-<i>x</i>) == ulp(<i>x</i>)</code>. 1462 * 1463 * <p>Special Cases: 1464 * <ul> 1465 * <li> If the argument is NaN, then the result is NaN. 1466 * <li> If the argument is positive or negative infinity, then the 1467 * result is positive infinity. 1468 * <li> If the argument is positive or negative zero, then the result is 1469 * {@code Float.MIN_VALUE}. 1470 * <li> If the argument is ±{@code Float.MAX_VALUE}, then 1471 * the result is equal to 2<sup>104</sup>. 1472 * </ul> 1473 * 1474 * @param f the floating-point value whose ulp is to be returned 1475 * @return the size of an ulp of the argument 1476 * @author Joseph D. Darcy 1477 * @since 1.5 1478 */ 1479 public static float ulp(float f) { 1480 int exp = getExponent(f); 1481 1482 switch(exp) { 1483 case FloatConsts.MAX_EXPONENT+1: // NaN or infinity 1484 return Math.abs(f); 1485 1486 case FloatConsts.MIN_EXPONENT-1: // zero or subnormal 1487 return FloatConsts.MIN_VALUE; 1488 1489 default: 1490 assert exp <= FloatConsts.MAX_EXPONENT && exp >= FloatConsts.MIN_EXPONENT; 1491 1492 // ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x)) 1493 exp = exp - (FloatConsts.SIGNIFICAND_WIDTH-1); 1494 if (exp >= FloatConsts.MIN_EXPONENT) { 1495 return powerOfTwoF(exp); 1496 } 1497 else { 1498 // return a subnormal result; left shift integer 1499 // representation of FloatConsts.MIN_VALUE appropriate 1500 // number of positions 1501 return Float.intBitsToFloat(1 << 1502 (exp - (FloatConsts.MIN_EXPONENT - (FloatConsts.SIGNIFICAND_WIDTH-1)) )); 1503 } 1504 } 1505 } 1506 1507 /** 1508 * Returns the signum function of the argument; zero if the argument 1509 * is zero, 1.0 if the argument is greater than zero, -1.0 if the 1510 * argument is less than zero. 1511 * 1512 * <p>Special Cases: 1513 * <ul> 1514 * <li> If the argument is NaN, then the result is NaN. 1515 * <li> If the argument is positive zero or negative zero, then the 1516 * result is the same as the argument. 1517 * </ul> 1518 * 1519 * @param d the floating-point value whose signum is to be returned 1520 * @return the signum function of the argument 1521 * @author Joseph D. Darcy 1522 * @since 1.5 1523 */ 1524 public static double signum(double d) { 1525 return (d == 0.0 || Double.isNaN(d))?d:copySign(1.0, d); 1526 } 1527 1528 /** 1529 * Returns the signum function of the argument; zero if the argument 1530 * is zero, 1.0f if the argument is greater than zero, -1.0f if the 1531 * argument is less than zero. 1532 * 1533 * <p>Special Cases: 1534 * <ul> 1535 * <li> If the argument is NaN, then the result is NaN. 1536 * <li> If the argument is positive zero or negative zero, then the 1537 * result is the same as the argument. 1538 * </ul> 1539 * 1540 * @param f the floating-point value whose signum is to be returned 1541 * @return the signum function of the argument 1542 * @author Joseph D. Darcy 1543 * @since 1.5 1544 */ 1545 public static float signum(float f) { 1546 return (f == 0.0f || Float.isNaN(f))?f:copySign(1.0f, f); 1547 } 1548 1549 /** 1550 * Returns the hyperbolic sine of a {@code double} value. 1551 * The hyperbolic sine of <i>x</i> is defined to be 1552 * (<i>e<sup>x</sup> - e<sup>-x</sup></i>)/2 1553 * where <i>e</i> is {@linkplain Math#E Euler's number}. 1554 * 1555 * <p>Special cases: 1556 * <ul> 1557 * 1558 * <li>If the argument is NaN, then the result is NaN. 1559 * 1560 * <li>If the argument is infinite, then the result is an infinity 1561 * with the same sign as the argument. 1562 * 1563 * <li>If the argument is zero, then the result is a zero with the 1564 * same sign as the argument. 1565 * 1566 * </ul> 1567 * 1568 * <p>The computed result must be within 2.5 ulps of the exact result. 1569 * 1570 * @param x The number whose hyperbolic sine is to be returned. 1571 * @return The hyperbolic sine of {@code x}. 1572 * @since 1.5 1573 */ 1574 public static double sinh(double x) { 1575 return StrictMath.sinh(x); 1576 } 1577 1578 /** 1579 * Returns the hyperbolic cosine of a {@code double} value. 1580 * The hyperbolic cosine of <i>x</i> is defined to be 1581 * (<i>e<sup>x</sup> + e<sup>-x</sup></i>)/2 1582 * where <i>e</i> is {@linkplain Math#E Euler's number}. 1583 * 1584 * <p>Special cases: 1585 * <ul> 1586 * 1587 * <li>If the argument is NaN, then the result is NaN. 1588 * 1589 * <li>If the argument is infinite, then the result is positive 1590 * infinity. 1591 * 1592 * <li>If the argument is zero, then the result is {@code 1.0}. 1593 * 1594 * </ul> 1595 * 1596 * <p>The computed result must be within 2.5 ulps of the exact result. 1597 * 1598 * @param x The number whose hyperbolic cosine is to be returned. 1599 * @return The hyperbolic cosine of {@code x}. 1600 * @since 1.5 1601 */ 1602 public static double cosh(double x) { 1603 return StrictMath.cosh(x); 1604 } 1605 1606 /** 1607 * Returns the hyperbolic tangent of a {@code double} value. 1608 * The hyperbolic tangent of <i>x</i> is defined to be 1609 * (<i>e<sup>x</sup> - e<sup>-x</sup></i>)/(<i>e<sup>x</sup> + e<sup>-x</sup></i>), 1610 * in other words, {@linkplain Math#sinh 1611 * sinh(<i>x</i>)}/{@linkplain Math#cosh cosh(<i>x</i>)}. Note 1612 * that the absolute value of the exact tanh is always less than 1613 * 1. 1614 * 1615 * <p>Special cases: 1616 * <ul> 1617 * 1618 * <li>If the argument is NaN, then the result is NaN. 1619 * 1620 * <li>If the argument is zero, then the result is a zero with the 1621 * same sign as the argument. 1622 * 1623 * <li>If the argument is positive infinity, then the result is 1624 * {@code +1.0}. 1625 * 1626 * <li>If the argument is negative infinity, then the result is 1627 * {@code -1.0}. 1628 * 1629 * </ul> 1630 * 1631 * <p>The computed result must be within 2.5 ulps of the exact result. 1632 * The result of {@code tanh} for any finite input must have 1633 * an absolute value less than or equal to 1. Note that once the 1634 * exact result of tanh is within 1/2 of an ulp of the limit value 1635 * of ±1, correctly signed ±{@code 1.0} should 1636 * be returned. 1637 * 1638 * @param x The number whose hyperbolic tangent is to be returned. 1639 * @return The hyperbolic tangent of {@code x}. 1640 * @since 1.5 1641 */ 1642 public static double tanh(double x) { 1643 return StrictMath.tanh(x); 1644 } 1645 1646 /** 1647 * Returns sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) 1648 * without intermediate overflow or underflow. 1649 * 1650 * <p>Special cases: 1651 * <ul> 1652 * 1653 * <li> If either argument is infinite, then the result 1654 * is positive infinity. 1655 * 1656 * <li> If either argument is NaN and neither argument is infinite, 1657 * then the result is NaN. 1658 * 1659 * </ul> 1660 * 1661 * <p>The computed result must be within 1 ulp of the exact 1662 * result. If one parameter is held constant, the results must be 1663 * semi-monotonic in the other parameter. 1664 * 1665 * @param x a value 1666 * @param y a value 1667 * @return sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) 1668 * without intermediate overflow or underflow 1669 * @since 1.5 1670 */ 1671 public static double hypot(double x, double y) { 1672 return StrictMath.hypot(x, y); 1673 } 1674 1675 /** 1676 * Returns <i>e</i><sup>x</sup> -1. Note that for values of 1677 * <i>x</i> near 0, the exact sum of 1678 * {@code expm1(x)} + 1 is much closer to the true 1679 * result of <i>e</i><sup>x</sup> than {@code exp(x)}. 1680 * 1681 * <p>Special cases: 1682 * <ul> 1683 * <li>If the argument is NaN, the result is NaN. 1684 * 1685 * <li>If the argument is positive infinity, then the result is 1686 * positive infinity. 1687 * 1688 * <li>If the argument is negative infinity, then the result is 1689 * -1.0. 1690 * 1691 * <li>If the argument is zero, then the result is a zero with the 1692 * same sign as the argument. 1693 * 1694 * </ul> 1695 * 1696 * <p>The computed result must be within 1 ulp of the exact result. 1697 * Results must be semi-monotonic. The result of 1698 * {@code expm1} for any finite input must be greater than or 1699 * equal to {@code -1.0}. Note that once the exact result of 1700 * <i>e</i><sup>{@code x}</sup> - 1 is within 1/2 1701 * ulp of the limit value -1, {@code -1.0} should be 1702 * returned. 1703 * 1704 * @param x the exponent to raise <i>e</i> to in the computation of 1705 * <i>e</i><sup>{@code x}</sup> -1. 1706 * @return the value <i>e</i><sup>{@code x}</sup> - 1. 1707 * @since 1.5 1708 */ 1709 public static double expm1(double x) { 1710 return StrictMath.expm1(x); 1711 } 1712 1713 /** 1714 * Returns the natural logarithm of the sum of the argument and 1. 1715 * Note that for small values {@code x}, the result of 1716 * {@code log1p(x)} is much closer to the true result of ln(1 1717 * + {@code x}) than the floating-point evaluation of 1718 * {@code log(1.0+x)}. 1719 * 1720 * <p>Special cases: 1721 * 1722 * <ul> 1723 * 1724 * <li>If the argument is NaN or less than -1, then the result is 1725 * NaN. 1726 * 1727 * <li>If the argument is positive infinity, then the result is 1728 * positive infinity. 1729 * 1730 * <li>If the argument is negative one, then the result is 1731 * negative infinity. 1732 * 1733 * <li>If the argument is zero, then the result is a zero with the 1734 * same sign as the argument. 1735 * 1736 * </ul> 1737 * 1738 * <p>The computed result must be within 1 ulp of the exact result. 1739 * Results must be semi-monotonic. 1740 * 1741 * @param x a value 1742 * @return the value ln({@code x} + 1), the natural 1743 * log of {@code x} + 1 1744 * @since 1.5 1745 */ 1746 public static double log1p(double x) { 1747 return StrictMath.log1p(x); 1748 } 1749 1750 /** 1751 * Returns the first floating-point argument with the sign of the 1752 * second floating-point argument. Note that unlike the {@link 1753 * StrictMath#copySign(double, double) StrictMath.copySign} 1754 * method, this method does not require NaN {@code sign} 1755 * arguments to be treated as positive values; implementations are 1756 * permitted to treat some NaN arguments as positive and other NaN 1757 * arguments as negative to allow greater performance. 1758 * 1759 * @param magnitude the parameter providing the magnitude of the result 1760 * @param sign the parameter providing the sign of the result 1761 * @return a value with the magnitude of {@code magnitude} 1762 * and the sign of {@code sign}. 1763 * @since 1.6 1764 */ 1765 public static double copySign(double magnitude, double sign) { 1766 return Double.longBitsToDouble((Double.doubleToRawLongBits(sign) & 1767 (DoubleConsts.SIGN_BIT_MASK)) | 1768 (Double.doubleToRawLongBits(magnitude) & 1769 (DoubleConsts.EXP_BIT_MASK | 1770 DoubleConsts.SIGNIF_BIT_MASK))); 1771 } 1772 1773 /** 1774 * Returns the first floating-point argument with the sign of the 1775 * second floating-point argument. Note that unlike the {@link 1776 * StrictMath#copySign(float, float) StrictMath.copySign} 1777 * method, this method does not require NaN {@code sign} 1778 * arguments to be treated as positive values; implementations are 1779 * permitted to treat some NaN arguments as positive and other NaN 1780 * arguments as negative to allow greater performance. 1781 * 1782 * @param magnitude the parameter providing the magnitude of the result 1783 * @param sign the parameter providing the sign of the result 1784 * @return a value with the magnitude of {@code magnitude} 1785 * and the sign of {@code sign}. 1786 * @since 1.6 1787 */ 1788 public static float copySign(float magnitude, float sign) { 1789 return Float.intBitsToFloat((Float.floatToRawIntBits(sign) & 1790 (FloatConsts.SIGN_BIT_MASK)) | 1791 (Float.floatToRawIntBits(magnitude) & 1792 (FloatConsts.EXP_BIT_MASK | 1793 FloatConsts.SIGNIF_BIT_MASK))); 1794 } 1795 1796 /** 1797 * Returns the unbiased exponent used in the representation of a 1798 * {@code float}. Special cases: 1799 * 1800 * <ul> 1801 * <li>If the argument is NaN or infinite, then the result is 1802 * {@link Float#MAX_EXPONENT} + 1. 1803 * <li>If the argument is zero or subnormal, then the result is 1804 * {@link Float#MIN_EXPONENT} -1. 1805 * </ul> 1806 * @param f a {@code float} value 1807 * @return the unbiased exponent of the argument 1808 * @since 1.6 1809 */ 1810 public static int getExponent(float f) { 1811 /* 1812 * Bitwise convert f to integer, mask out exponent bits, shift 1813 * to the right and then subtract out float's bias adjust to 1814 * get true exponent value 1815 */ 1816 return ((Float.floatToRawIntBits(f) & FloatConsts.EXP_BIT_MASK) >> 1817 (FloatConsts.SIGNIFICAND_WIDTH - 1)) - FloatConsts.EXP_BIAS; 1818 } 1819 1820 /** 1821 * Returns the unbiased exponent used in the representation of a 1822 * {@code double}. Special cases: 1823 * 1824 * <ul> 1825 * <li>If the argument is NaN or infinite, then the result is 1826 * {@link Double#MAX_EXPONENT} + 1. 1827 * <li>If the argument is zero or subnormal, then the result is 1828 * {@link Double#MIN_EXPONENT} -1. 1829 * </ul> 1830 * @param d a {@code double} value 1831 * @return the unbiased exponent of the argument 1832 * @since 1.6 1833 */ 1834 public static int getExponent(double d) { 1835 /* 1836 * Bitwise convert d to long, mask out exponent bits, shift 1837 * to the right and then subtract out double's bias adjust to 1838 * get true exponent value. 1839 */ 1840 return (int)(((Double.doubleToRawLongBits(d) & DoubleConsts.EXP_BIT_MASK) >> 1841 (DoubleConsts.SIGNIFICAND_WIDTH - 1)) - DoubleConsts.EXP_BIAS); 1842 } 1843 1844 /** 1845 * Returns the floating-point number adjacent to the first 1846 * argument in the direction of the second argument. If both 1847 * arguments compare as equal the second argument is returned. 1848 * 1849 * <p> 1850 * Special cases: 1851 * <ul> 1852 * <li> If either argument is a NaN, then NaN is returned. 1853 * 1854 * <li> If both arguments are signed zeros, {@code direction} 1855 * is returned unchanged (as implied by the requirement of 1856 * returning the second argument if the arguments compare as 1857 * equal). 1858 * 1859 * <li> If {@code start} is 1860 * ±{@link Double#MIN_VALUE} and {@code direction} 1861 * has a value such that the result should have a smaller 1862 * magnitude, then a zero with the same sign as {@code start} 1863 * is returned. 1864 * 1865 * <li> If {@code start} is infinite and 1866 * {@code direction} has a value such that the result should 1867 * have a smaller magnitude, {@link Double#MAX_VALUE} with the 1868 * same sign as {@code start} is returned. 1869 * 1870 * <li> If {@code start} is equal to ± 1871 * {@link Double#MAX_VALUE} and {@code direction} has a 1872 * value such that the result should have a larger magnitude, an 1873 * infinity with same sign as {@code start} is returned. 1874 * </ul> 1875 * 1876 * @param start starting floating-point value 1877 * @param direction value indicating which of 1878 * {@code start}'s neighbors or {@code start} should 1879 * be returned 1880 * @return The floating-point number adjacent to {@code start} in the 1881 * direction of {@code direction}. 1882 * @since 1.6 1883 */ 1884 public static double nextAfter(double start, double direction) { 1885 /* 1886 * The cases: 1887 * 1888 * nextAfter(+infinity, 0) == MAX_VALUE 1889 * nextAfter(+infinity, +infinity) == +infinity 1890 * nextAfter(-infinity, 0) == -MAX_VALUE 1891 * nextAfter(-infinity, -infinity) == -infinity 1892 * 1893 * are naturally handled without any additional testing 1894 */ 1895 1896 // First check for NaN values 1897 if (Double.isNaN(start) || Double.isNaN(direction)) { 1898 // return a NaN derived from the input NaN(s) 1899 return start + direction; 1900 } else if (start == direction) { 1901 return direction; 1902 } else { // start > direction or start < direction 1903 // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0) 1904 // then bitwise convert start to integer. 1905 long transducer = Double.doubleToRawLongBits(start + 0.0d); 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 values 1915 * is less than zero, the adjustment to the representation 1916 * is in the opposite direction than would be expected at 1917 * first . 1918 */ 1919 if (direction > start) { // Calculate next greater value 1920 transducer = transducer + (transducer >= 0L ? 1L:-1L); 1921 } else { // Calculate next lesser value 1922 assert direction < start; 1923 if (transducer > 0L) 1924 --transducer; 1925 else 1926 if (transducer < 0L ) 1927 ++transducer; 1928 /* 1929 * transducer==0, the result is -MIN_VALUE 1930 * 1931 * The transition from zero (implicitly 1932 * positive) to the smallest negative 1933 * signed magnitude value must be done 1934 * explicitly. 1935 */ 1936 else 1937 transducer = DoubleConsts.SIGN_BIT_MASK | 1L; 1938 } 1939 1940 return Double.longBitsToDouble(transducer); 1941 } 1942 } 1943 1944 /** 1945 * Returns the floating-point number adjacent to the first 1946 * argument in the direction of the second argument. If both 1947 * arguments compare as equal a value equivalent to the second argument 1948 * is returned. 1949 * 1950 * <p> 1951 * Special cases: 1952 * <ul> 1953 * <li> If either argument is a NaN, then NaN is returned. 1954 * 1955 * <li> If both arguments are signed zeros, a value equivalent 1956 * to {@code direction} is returned. 1957 * 1958 * <li> If {@code start} is 1959 * ±{@link Float#MIN_VALUE} and {@code direction} 1960 * has a value such that the result should have a smaller 1961 * magnitude, then a zero with the same sign as {@code start} 1962 * is returned. 1963 * 1964 * <li> If {@code start} is infinite and 1965 * {@code direction} has a value such that the result should 1966 * have a smaller magnitude, {@link Float#MAX_VALUE} with the 1967 * same sign as {@code start} is returned. 1968 * 1969 * <li> If {@code start} is equal to ± 1970 * {@link Float#MAX_VALUE} and {@code direction} has a 1971 * value such that the result should have a larger magnitude, an 1972 * infinity with same sign as {@code start} is returned. 1973 * </ul> 1974 * 1975 * @param start starting floating-point value 1976 * @param direction value indicating which of 1977 * {@code start}'s neighbors or {@code start} should 1978 * be returned 1979 * @return The floating-point number adjacent to {@code start} in the 1980 * direction of {@code direction}. 1981 * @since 1.6 1982 */ 1983 public static float nextAfter(float start, double direction) { 1984 /* 1985 * The cases: 1986 * 1987 * nextAfter(+infinity, 0) == MAX_VALUE 1988 * nextAfter(+infinity, +infinity) == +infinity 1989 * nextAfter(-infinity, 0) == -MAX_VALUE 1990 * nextAfter(-infinity, -infinity) == -infinity 1991 * 1992 * are naturally handled without any additional testing 1993 */ 1994 1995 // First check for NaN values 1996 if (Float.isNaN(start) || Double.isNaN(direction)) { 1997 // return a NaN derived from the input NaN(s) 1998 return start + (float)direction; 1999 } else if (start == direction) { 2000 return (float)direction; 2001 } else { // start > direction or start < direction 2002 // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0) 2003 // then bitwise convert start to integer. 2004 int transducer = Float.floatToRawIntBits(start + 0.0f); 2005 2006 /* 2007 * IEEE 754 floating-point numbers are lexicographically 2008 * ordered if treated as signed- magnitude integers . 2009 * Since Java's integers are two's complement, 2010 * incrementing" the two's complement representation of a 2011 * logically negative floating-point value *decrements* 2012 * the signed-magnitude representation. Therefore, when 2013 * the integer representation of a floating-point values 2014 * is less than zero, the adjustment to the representation 2015 * is in the opposite direction than would be expected at 2016 * first. 2017 */ 2018 if (direction > start) {// Calculate next greater value 2019 transducer = transducer + (transducer >= 0 ? 1:-1); 2020 } else { // Calculate next lesser value 2021 assert direction < start; 2022 if (transducer > 0) 2023 --transducer; 2024 else 2025 if (transducer < 0 ) 2026 ++transducer; 2027 /* 2028 * transducer==0, the result is -MIN_VALUE 2029 * 2030 * The transition from zero (implicitly 2031 * positive) to the smallest negative 2032 * signed magnitude value must be done 2033 * explicitly. 2034 */ 2035 else 2036 transducer = FloatConsts.SIGN_BIT_MASK | 1; 2037 } 2038 2039 return Float.intBitsToFloat(transducer); 2040 } 2041 } 2042 2043 /** 2044 * Returns the floating-point value adjacent to {@code d} in 2045 * the direction of positive infinity. This method is 2046 * semantically equivalent to {@code nextAfter(d, 2047 * Double.POSITIVE_INFINITY)}; however, a {@code nextUp} 2048 * implementation may run faster than its equivalent 2049 * {@code nextAfter} call. 2050 * 2051 * <p>Special Cases: 2052 * <ul> 2053 * <li> If the argument is NaN, the result is NaN. 2054 * 2055 * <li> If the argument is positive infinity, the result is 2056 * positive infinity. 2057 * 2058 * <li> If the argument is zero, the result is 2059 * {@link Double#MIN_VALUE} 2060 * 2061 * </ul> 2062 * 2063 * @param d starting floating-point value 2064 * @return The adjacent floating-point value closer to positive 2065 * infinity. 2066 * @since 1.6 2067 */ 2068 public static double nextUp(double d) { 2069 if( Double.isNaN(d) || d == Double.POSITIVE_INFINITY) 2070 return d; 2071 else { 2072 d += 0.0d; 2073 return Double.longBitsToDouble(Double.doubleToRawLongBits(d) + 2074 ((d >= 0.0d)?+1L:-1L)); 2075 } 2076 } 2077 2078 /** 2079 * Returns the floating-point value adjacent to {@code f} in 2080 * the direction of positive infinity. This method is 2081 * semantically equivalent to {@code nextAfter(f, 2082 * Float.POSITIVE_INFINITY)}; however, a {@code nextUp} 2083 * implementation may run faster than its equivalent 2084 * {@code nextAfter} call. 2085 * 2086 * <p>Special Cases: 2087 * <ul> 2088 * <li> If the argument is NaN, the result is NaN. 2089 * 2090 * <li> If the argument is positive infinity, the result is 2091 * positive infinity. 2092 * 2093 * <li> If the argument is zero, the result is 2094 * {@link Float#MIN_VALUE} 2095 * 2096 * </ul> 2097 * 2098 * @param f starting floating-point value 2099 * @return The adjacent floating-point value closer to positive 2100 * infinity. 2101 * @since 1.6 2102 */ 2103 public static float nextUp(float f) { 2104 if( Float.isNaN(f) || f == FloatConsts.POSITIVE_INFINITY) 2105 return f; 2106 else { 2107 f += 0.0f; 2108 return Float.intBitsToFloat(Float.floatToRawIntBits(f) + 2109 ((f >= 0.0f)?+1:-1)); 2110 } 2111 } 2112 2113 /** 2114 * Returns the floating-point value adjacent to {@code d} in 2115 * the direction of negative infinity. This method is 2116 * semantically equivalent to {@code nextAfter(d, 2117 * Double.NEGATIVE_INFINITY)}; however, a 2118 * {@code nextDown} implementation may run faster than its 2119 * equivalent {@code nextAfter} call. 2120 * 2121 * <p>Special Cases: 2122 * <ul> 2123 * <li> If the argument is NaN, the result is NaN. 2124 * 2125 * <li> If the argument is negative infinity, the result is 2126 * negative infinity. 2127 * 2128 * <li> If the argument is zero, the result is 2129 * {@code -Double.MIN_VALUE} 2130 * 2131 * </ul> 2132 * 2133 * @param d starting floating-point value 2134 * @return The adjacent floating-point value closer to negative 2135 * infinity. 2136 * @since 1.8 2137 */ 2138 public static double nextDown(double d) { 2139 if (Double.isNaN(d) || d == Double.NEGATIVE_INFINITY) 2140 return d; 2141 else { 2142 if (d == 0.0) 2143 return -Double.MIN_VALUE; 2144 else 2145 return Double.longBitsToDouble(Double.doubleToRawLongBits(d) + 2146 ((d > 0.0d)?-1L:+1L)); 2147 } 2148 } 2149 2150 /** 2151 * Returns the floating-point value adjacent to {@code f} in 2152 * the direction of negative infinity. This method is 2153 * semantically equivalent to {@code nextAfter(f, 2154 * Float.NEGATIVE_INFINITY)}; however, a 2155 * {@code nextDown} implementation may run faster than its 2156 * equivalent {@code nextAfter} call. 2157 * 2158 * <p>Special Cases: 2159 * <ul> 2160 * <li> If the argument is NaN, the result is NaN. 2161 * 2162 * <li> If the argument is negative infinity, the result is 2163 * negative infinity. 2164 * 2165 * <li> If the argument is zero, the result is 2166 * {@code -Float.MIN_VALUE} 2167 * 2168 * </ul> 2169 * 2170 * @param f starting floating-point value 2171 * @return The adjacent floating-point value closer to negative 2172 * infinity. 2173 * @since 1.8 2174 */ 2175 public static float nextDown(float f) { 2176 if (Float.isNaN(f) || f == Float.NEGATIVE_INFINITY) 2177 return f; 2178 else { 2179 if (f == 0.0f) 2180 return -Float.MIN_VALUE; 2181 else 2182 return Float.intBitsToFloat(Float.floatToRawIntBits(f) + 2183 ((f > 0.0f)?-1:+1)); 2184 } 2185 } 2186 2187 /** 2188 * Returns {@code d} × 2189 * 2<sup>{@code scaleFactor}</sup> rounded as if performed 2190 * by a single correctly rounded floating-point multiply to a 2191 * member of the double value set. See the Java 2192 * Language Specification for a discussion of floating-point 2193 * value sets. If the exponent of the result is between {@link 2194 * Double#MIN_EXPONENT} and {@link Double#MAX_EXPONENT}, the 2195 * answer is calculated exactly. If the exponent of the result 2196 * would be larger than {@code Double.MAX_EXPONENT}, an 2197 * infinity is returned. Note that if the result is subnormal, 2198 * precision may be lost; that is, when {@code scalb(x, n)} 2199 * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal 2200 * <i>x</i>. When the result is non-NaN, the result has the same 2201 * sign as {@code d}. 2202 * 2203 * <p>Special cases: 2204 * <ul> 2205 * <li> If the first argument is NaN, NaN is returned. 2206 * <li> If the first argument is infinite, then an infinity of the 2207 * same sign is returned. 2208 * <li> If the first argument is zero, then a zero of the same 2209 * sign is returned. 2210 * </ul> 2211 * 2212 * @param d number to be scaled by a power of two. 2213 * @param scaleFactor power of 2 used to scale {@code d} 2214 * @return {@code d} × 2<sup>{@code scaleFactor}</sup> 2215 * @since 1.6 2216 */ 2217 public static double scalb(double d, int scaleFactor) { 2218 /* 2219 * This method does not need to be declared strictfp to 2220 * compute the same correct result on all platforms. When 2221 * scaling up, it does not matter what order the 2222 * multiply-store operations are done; the result will be 2223 * finite or overflow regardless of the operation ordering. 2224 * However, to get the correct result when scaling down, a 2225 * particular ordering must be used. 2226 * 2227 * When scaling down, the multiply-store operations are 2228 * sequenced so that it is not possible for two consecutive 2229 * multiply-stores to return subnormal results. If one 2230 * multiply-store result is subnormal, the next multiply will 2231 * round it away to zero. This is done by first multiplying 2232 * by 2 ^ (scaleFactor % n) and then multiplying several 2233 * times by by 2^n as needed where n is the exponent of number 2234 * that is a covenient power of two. In this way, at most one 2235 * real rounding error occurs. If the double value set is 2236 * being used exclusively, the rounding will occur on a 2237 * multiply. If the double-extended-exponent value set is 2238 * being used, the products will (perhaps) be exact but the 2239 * stores to d are guaranteed to round to the double value 2240 * set. 2241 * 2242 * It is _not_ a valid implementation to first multiply d by 2243 * 2^MIN_EXPONENT and then by 2 ^ (scaleFactor % 2244 * MIN_EXPONENT) since even in a strictfp program double 2245 * rounding on underflow could occur; e.g. if the scaleFactor 2246 * argument was (MIN_EXPONENT - n) and the exponent of d was a 2247 * little less than -(MIN_EXPONENT - n), meaning the final 2248 * result would be subnormal. 2249 * 2250 * Since exact reproducibility of this method can be achieved 2251 * without any undue performance burden, there is no 2252 * compelling reason to allow double rounding on underflow in 2253 * scalb. 2254 */ 2255 2256 // magnitude of a power of two so large that scaling a finite 2257 // nonzero value by it would be guaranteed to over or 2258 // underflow; due to rounding, scaling down takes takes an 2259 // additional power of two which is reflected here 2260 final int MAX_SCALE = DoubleConsts.MAX_EXPONENT + -DoubleConsts.MIN_EXPONENT + 2261 DoubleConsts.SIGNIFICAND_WIDTH + 1; 2262 int exp_adjust = 0; 2263 int scale_increment = 0; 2264 double exp_delta = Double.NaN; 2265 2266 // Make sure scaling factor is in a reasonable range 2267 2268 if(scaleFactor < 0) { 2269 scaleFactor = Math.max(scaleFactor, -MAX_SCALE); 2270 scale_increment = -512; 2271 exp_delta = twoToTheDoubleScaleDown; 2272 } 2273 else { 2274 scaleFactor = Math.min(scaleFactor, MAX_SCALE); 2275 scale_increment = 512; 2276 exp_delta = twoToTheDoubleScaleUp; 2277 } 2278 2279 // Calculate (scaleFactor % +/-512), 512 = 2^9, using 2280 // technique from "Hacker's Delight" section 10-2. 2281 int t = (scaleFactor >> 9-1) >>> 32 - 9; 2282 exp_adjust = ((scaleFactor + t) & (512 -1)) - t; 2283 2284 d *= powerOfTwoD(exp_adjust); 2285 scaleFactor -= exp_adjust; 2286 2287 while(scaleFactor != 0) { 2288 d *= exp_delta; 2289 scaleFactor -= scale_increment; 2290 } 2291 return d; 2292 } 2293 2294 /** 2295 * Returns {@code f} × 2296 * 2<sup>{@code scaleFactor}</sup> rounded as if performed 2297 * by a single correctly rounded floating-point multiply to a 2298 * member of the float value set. See the Java 2299 * Language Specification for a discussion of floating-point 2300 * value sets. If the exponent of the result is between {@link 2301 * Float#MIN_EXPONENT} and {@link Float#MAX_EXPONENT}, the 2302 * answer is calculated exactly. If the exponent of the result 2303 * would be larger than {@code Float.MAX_EXPONENT}, an 2304 * infinity is returned. Note that if the result is subnormal, 2305 * precision may be lost; that is, when {@code scalb(x, n)} 2306 * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal 2307 * <i>x</i>. When the result is non-NaN, the result has the same 2308 * sign as {@code f}. 2309 * 2310 * <p>Special cases: 2311 * <ul> 2312 * <li> If the first argument is NaN, NaN is returned. 2313 * <li> If the first argument is infinite, then an infinity of the 2314 * same sign is returned. 2315 * <li> If the first argument is zero, then a zero of the same 2316 * sign is returned. 2317 * </ul> 2318 * 2319 * @param f number to be scaled by a power of two. 2320 * @param scaleFactor power of 2 used to scale {@code f} 2321 * @return {@code f} × 2<sup>{@code scaleFactor}</sup> 2322 * @since 1.6 2323 */ 2324 public static float scalb(float f, int scaleFactor) { 2325 // magnitude of a power of two so large that scaling a finite 2326 // nonzero value by it would be guaranteed to over or 2327 // underflow; due to rounding, scaling down takes takes an 2328 // additional power of two which is reflected here 2329 final int MAX_SCALE = FloatConsts.MAX_EXPONENT + -FloatConsts.MIN_EXPONENT + 2330 FloatConsts.SIGNIFICAND_WIDTH + 1; 2331 2332 // Make sure scaling factor is in a reasonable range 2333 scaleFactor = Math.max(Math.min(scaleFactor, MAX_SCALE), -MAX_SCALE); 2334 2335 /* 2336 * Since + MAX_SCALE for float fits well within the double 2337 * exponent range and + float -> double conversion is exact 2338 * the multiplication below will be exact. Therefore, the 2339 * rounding that occurs when the double product is cast to 2340 * float will be the correctly rounded float result. Since 2341 * all operations other than the final multiply will be exact, 2342 * it is not necessary to declare this method strictfp. 2343 */ 2344 return (float)((double)f*powerOfTwoD(scaleFactor)); 2345 } 2346 2347 // Constants used in scalb 2348 static double twoToTheDoubleScaleUp = powerOfTwoD(512); 2349 static double twoToTheDoubleScaleDown = powerOfTwoD(-512); 2350 2351 /** 2352 * Returns a floating-point power of two in the normal range. 2353 */ 2354 static double powerOfTwoD(int n) { 2355 assert(n >= DoubleConsts.MIN_EXPONENT && n <= DoubleConsts.MAX_EXPONENT); 2356 return Double.longBitsToDouble((((long)n + (long)DoubleConsts.EXP_BIAS) << 2357 (DoubleConsts.SIGNIFICAND_WIDTH-1)) 2358 & DoubleConsts.EXP_BIT_MASK); 2359 } 2360 2361 /** 2362 * Returns a floating-point power of two in the normal range. 2363 */ 2364 static float powerOfTwoF(int n) { 2365 assert(n >= FloatConsts.MIN_EXPONENT && n <= FloatConsts.MAX_EXPONENT); 2366 return Float.intBitsToFloat(((n + FloatConsts.EXP_BIAS) << 2367 (FloatConsts.SIGNIFICAND_WIDTH-1)) 2368 & FloatConsts.EXP_BIT_MASK); 2369 } 2370 }