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