1 /* 2 * Copyright (c) 1994, 2011, 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 * @author unascribed 85 * @author Joseph D. Darcy 86 * @since JDK1.0 87 */ 88 89 public final class Math { 90 91 /** 92 * Don't let anyone instantiate this class. 93 */ 94 private Math() {} 95 96 /** 97 * The {@code double} value that is closer than any other to 98 * <i>e</i>, the base of the natural logarithms. 99 */ 100 public static final double E = 2.7182818284590452354; 101 102 /** 103 * The {@code double} value that is closer than any other to 104 * <i>pi</i>, the ratio of the circumference of a circle to its 105 * diameter. 106 */ 107 public static final double PI = 3.14159265358979323846; 108 109 /** 110 * Returns the trigonometric sine of an angle. Special cases: 111 * <ul><li>If the argument is NaN or an infinity, then the 112 * result is NaN. 113 * <li>If the argument is zero, then the result is a zero with the 114 * same sign as the argument.</ul> 115 * 116 * <p>The computed result must be within 1 ulp of the exact result. 117 * Results must be semi-monotonic. 118 * 119 * @param a an angle, in radians. 120 * @return the sine of the argument. 121 */ 122 public static double sin(double a) { 123 return StrictMath.sin(a); // default impl. delegates to StrictMath 124 } 125 126 /** 127 * Returns the trigonometric cosine of an angle. Special cases: 128 * <ul><li>If the argument is NaN or an infinity, then the 129 * result is NaN.</ul> 130 * 131 * <p>The computed result must be within 1 ulp of the exact result. 132 * Results must be semi-monotonic. 133 * 134 * @param a an angle, in radians. 135 * @return the cosine of the argument. 136 */ 137 public static double cos(double a) { 138 return StrictMath.cos(a); // default impl. delegates to StrictMath 139 } 140 141 /** 142 * Returns the trigonometric tangent of an angle. Special cases: 143 * <ul><li>If the argument is NaN or an infinity, then the result 144 * is NaN. 145 * <li>If the argument is zero, then the result is a zero with the 146 * same sign as the argument.</ul> 147 * 148 * <p>The computed result must be within 1 ulp of the exact result. 149 * Results must be semi-monotonic. 150 * 151 * @param a an angle, in radians. 152 * @return the tangent of the argument. 153 */ 154 public static double tan(double a) { 155 return StrictMath.tan(a); // default impl. delegates to StrictMath 156 } 157 158 /** 159 * Returns the arc sine of a value; the returned angle is in the 160 * range -<i>pi</i>/2 through <i>pi</i>/2. Special cases: 161 * <ul><li>If the argument is NaN or its absolute value is greater 162 * than 1, then the result is NaN. 163 * <li>If the argument is zero, then the result is a zero with the 164 * same sign as the argument.</ul> 165 * 166 * <p>The computed result must be within 1 ulp of the exact result. 167 * Results must be semi-monotonic. 168 * 169 * @param a the value whose arc sine is to be returned. 170 * @return the arc sine of the argument. 171 */ 172 public static double asin(double a) { 173 return StrictMath.asin(a); // default impl. delegates to StrictMath 174 } 175 176 /** 177 * Returns the arc cosine of a value; the returned angle is in the 178 * range 0.0 through <i>pi</i>. Special case: 179 * <ul><li>If the argument is NaN or its absolute value is greater 180 * than 1, then the result is NaN.</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 cosine is to be returned. 186 * @return the arc cosine of the argument. 187 */ 188 public static double acos(double a) { 189 return StrictMath.acos(a); // default impl. delegates to StrictMath 190 } 191 192 /** 193 * Returns the arc tangent of a value; the returned angle is in the 194 * range -<i>pi</i>/2 through <i>pi</i>/2. Special cases: 195 * <ul><li>If the argument is NaN, then the result is NaN. 196 * <li>If the argument is zero, then the result is a zero with the 197 * same sign as the argument.</ul> 198 * 199 * <p>The computed result must be within 1 ulp of the exact result. 200 * Results must be semi-monotonic. 201 * 202 * @param a the value whose arc tangent is to be returned. 203 * @return the arc tangent of the argument. 204 */ 205 public static double atan(double a) { 206 return StrictMath.atan(a); // default impl. delegates to StrictMath 207 } 208 209 /** 210 * Converts an angle measured in degrees to an approximately 211 * equivalent angle measured in radians. The conversion from 212 * degrees to radians is generally inexact. 213 * 214 * @param angdeg an angle, in degrees 215 * @return the measurement of the angle {@code angdeg} 216 * in radians. 217 * @since 1.2 218 */ 219 public static double toRadians(double angdeg) { 220 return angdeg / 180.0 * PI; 221 } 222 223 /** 224 * Converts an angle measured in radians to an approximately 225 * equivalent angle measured in degrees. The conversion from 226 * radians to degrees is generally inexact; users should 227 * <i>not</i> expect {@code cos(toRadians(90.0))} to exactly 228 * equal {@code 0.0}. 229 * 230 * @param angrad an angle, in radians 231 * @return the measurement of the angle {@code angrad} 232 * in degrees. 233 * @since 1.2 234 */ 235 public static double toDegrees(double angrad) { 236 return angrad * 180.0 / PI; 237 } 238 239 /** 240 * Returns Euler's number <i>e</i> raised to the power of a 241 * {@code double} value. Special cases: 242 * <ul><li>If the argument is NaN, the result is NaN. 243 * <li>If the argument is positive infinity, then the result is 244 * positive infinity. 245 * <li>If the argument is negative infinity, then the result is 246 * positive zero.</ul> 247 * 248 * <p>The computed result must be within 1 ulp of the exact result. 249 * Results must be semi-monotonic. 250 * 251 * @param a the exponent to raise <i>e</i> to. 252 * @return the value <i>e</i><sup>{@code a}</sup>, 253 * where <i>e</i> is the base of the natural logarithms. 254 */ 255 public static double exp(double a) { 256 return StrictMath.exp(a); // default impl. delegates to StrictMath 257 } 258 259 /** 260 * Returns the natural logarithm (base <i>e</i>) of a {@code double} 261 * value. Special cases: 262 * <ul><li>If the argument is NaN or less than zero, then the result 263 * is NaN. 264 * <li>If the argument is positive infinity, then the result is 265 * positive infinity. 266 * <li>If the argument is positive zero or negative zero, then the 267 * result is negative infinity.</ul> 268 * 269 * <p>The computed result must be within 1 ulp of the exact result. 270 * Results must be semi-monotonic. 271 * 272 * @param a a value 273 * @return the value ln {@code a}, the natural logarithm of 274 * {@code a}. 275 */ 276 public static double log(double a) { 277 return StrictMath.log(a); // default impl. delegates to StrictMath 278 } 279 280 /** 281 * Returns the base 10 logarithm of a {@code double} value. 282 * Special cases: 283 * 284 * <ul><li>If the argument is NaN or less than zero, then the result 285 * is NaN. 286 * <li>If the argument is positive infinity, then the result is 287 * positive infinity. 288 * <li>If the argument is positive zero or negative zero, then the 289 * result is negative infinity. 290 * <li> If the argument is equal to 10<sup><i>n</i></sup> for 291 * integer <i>n</i>, then the result is <i>n</i>. 292 * </ul> 293 * 294 * <p>The computed result must be within 1 ulp of the exact result. 295 * Results must be semi-monotonic. 296 * 297 * @param a a value 298 * @return the base 10 logarithm of {@code a}. 299 * @since 1.5 300 */ 301 public static double log10(double a) { 302 return StrictMath.log10(a); // default impl. delegates to StrictMath 303 } 304 305 /** 306 * Returns the correctly rounded positive square root of a 307 * {@code double} value. 308 * Special cases: 309 * <ul><li>If the argument is NaN or less than zero, then the result 310 * is NaN. 311 * <li>If the argument is positive infinity, then the result is positive 312 * infinity. 313 * <li>If the argument is positive zero or negative zero, then the 314 * result is the same as the argument.</ul> 315 * Otherwise, the result is the {@code double} value closest to 316 * the true mathematical square root of the argument value. 317 * 318 * @param a a value. 319 * @return the positive square root of {@code a}. 320 * If the argument is NaN or less than zero, the result is NaN. 321 */ 322 public static double sqrt(double a) { 323 return StrictMath.sqrt(a); // default impl. delegates to StrictMath 324 // Note that hardware sqrt instructions 325 // frequently can be directly used by JITs 326 // and should be much faster than doing 327 // Math.sqrt in software. 328 } 329 330 331 /** 332 * Returns the cube root of a {@code double} value. For 333 * positive finite {@code x}, {@code cbrt(-x) == 334 * -cbrt(x)}; that is, the cube root of a negative value is 335 * the negative of the cube root of that value's magnitude. 336 * 337 * Special cases: 338 * 339 * <ul> 340 * 341 * <li>If the argument is NaN, then the result is NaN. 342 * 343 * <li>If the argument is infinite, then the result is an infinity 344 * with the same sign as the argument. 345 * 346 * <li>If the argument is zero, then the result is a zero with the 347 * same sign as the argument. 348 * 349 * </ul> 350 * 351 * <p>The computed result must be within 1 ulp of the exact result. 352 * 353 * @param a a value. 354 * @return the cube root of {@code a}. 355 * @since 1.5 356 */ 357 public static double cbrt(double a) { 358 return StrictMath.cbrt(a); 359 } 360 361 /** 362 * Computes the remainder operation on two arguments as prescribed 363 * by the IEEE 754 standard. 364 * The remainder value is mathematically equal to 365 * <code>f1 - f2</code> × <i>n</i>, 366 * where <i>n</i> is the mathematical integer closest to the exact 367 * mathematical value of the quotient {@code f1/f2}, and if two 368 * mathematical integers are equally close to {@code f1/f2}, 369 * then <i>n</i> is the integer that is even. If the remainder is 370 * zero, its sign is the same as the sign of the first argument. 371 * Special cases: 372 * <ul><li>If either argument is NaN, or the first argument is infinite, 373 * or the second argument is positive zero or negative zero, then the 374 * result is NaN. 375 * <li>If the first argument is finite and the second argument is 376 * infinite, then the result is the same as the first argument.</ul> 377 * 378 * @param f1 the dividend. 379 * @param f2 the divisor. 380 * @return the remainder when {@code f1} is divided by 381 * {@code f2}. 382 */ 383 public static double IEEEremainder(double f1, double f2) { 384 return StrictMath.IEEEremainder(f1, f2); // delegate to StrictMath 385 } 386 387 /** 388 * Returns the smallest (closest to negative infinity) 389 * {@code double} value that is greater than or equal to the 390 * argument and is equal to a mathematical integer. Special cases: 391 * <ul><li>If the argument value is already equal to a 392 * mathematical integer, then the result is the same as the 393 * argument. <li>If the argument is NaN or an infinity or 394 * positive zero or negative zero, then the result is the same as 395 * the argument. <li>If the argument value is less than zero but 396 * greater than -1.0, then the result is negative zero.</ul> Note 397 * that the value of {@code Math.ceil(x)} is exactly the 398 * value of {@code -Math.floor(-x)}. 399 * 400 * 401 * @param a a value. 402 * @return the smallest (closest to negative infinity) 403 * floating-point value that is greater than or equal to 404 * the argument and is equal to a mathematical integer. 405 */ 406 public static double ceil(double a) { 407 return StrictMath.ceil(a); // default impl. delegates to StrictMath 408 } 409 410 /** 411 * Returns the largest (closest to positive infinity) 412 * {@code double} value that is less than or equal to the 413 * argument and is equal to a mathematical integer. Special cases: 414 * <ul><li>If the argument value is already equal to a 415 * mathematical integer, then the result is the same as the 416 * argument. <li>If the argument is NaN or an infinity or 417 * positive zero or negative zero, then the result is the same as 418 * the argument.</ul> 419 * 420 * @param a a value. 421 * @return the largest (closest to positive infinity) 422 * floating-point value that less than or equal to the argument 423 * and is equal to a mathematical integer. 424 */ 425 public static double floor(double a) { 426 return StrictMath.floor(a); // default impl. delegates to StrictMath 427 } 428 429 /** 430 * Returns the {@code double} value that is closest in value 431 * to the argument and is equal to a mathematical integer. If two 432 * {@code double} values that are mathematical integers are 433 * equally close, the result is the integer value that is 434 * even. Special cases: 435 * <ul><li>If the argument value is already equal to a mathematical 436 * integer, then the result is the same as the argument. 437 * <li>If the argument is NaN or an infinity or positive zero or negative 438 * zero, then the result is the same as the argument.</ul> 439 * 440 * @param a a {@code double} value. 441 * @return the closest floating-point value to {@code a} that is 442 * equal to a mathematical integer. 443 */ 444 public static double rint(double a) { 445 return StrictMath.rint(a); // default impl. delegates to StrictMath 446 } 447 448 /** 449 * Returns the angle <i>theta</i> from the conversion of rectangular 450 * coordinates ({@code x}, {@code y}) to polar 451 * coordinates (r, <i>theta</i>). 452 * This method computes the phase <i>theta</i> by computing an arc tangent 453 * of {@code y/x} in the range of -<i>pi</i> to <i>pi</i>. Special 454 * cases: 455 * <ul><li>If either argument is NaN, then the result is NaN. 456 * <li>If the first argument is positive zero and the second argument 457 * is positive, or the first argument is positive and finite and the 458 * second argument is positive infinity, then the result is positive 459 * zero. 460 * <li>If the first argument is negative zero and the second argument 461 * is positive, or the first argument is negative and finite and the 462 * second argument is positive infinity, then the result is negative zero. 463 * <li>If the first argument is positive zero and the second argument 464 * is negative, or the first argument is positive and finite and the 465 * second argument is negative infinity, then the result is the 466 * {@code double} value closest to <i>pi</i>. 467 * <li>If the first argument is negative zero and the second argument 468 * is negative, or the first argument is negative and finite and the 469 * second argument is negative infinity, then the result is the 470 * {@code double} value closest to -<i>pi</i>. 471 * <li>If the first argument is positive and the second argument is 472 * positive zero or negative zero, or the first argument is positive 473 * infinity and the second argument is finite, then the result is the 474 * {@code double} value closest to <i>pi</i>/2. 475 * <li>If the first argument is negative and the second argument is 476 * positive zero or negative zero, or the first argument is negative 477 * infinity and the second argument is finite, then the result is the 478 * {@code double} value closest to -<i>pi</i>/2. 479 * <li>If both arguments are positive infinity, then the result is the 480 * {@code double} value closest to <i>pi</i>/4. 481 * <li>If the first argument is positive infinity and the second argument 482 * is negative infinity, then the result is the {@code double} 483 * value closest to 3*<i>pi</i>/4. 484 * <li>If the first argument is negative infinity and the second argument 485 * is positive infinity, then the result is the {@code double} value 486 * closest to -<i>pi</i>/4. 487 * <li>If both arguments are negative infinity, then the result is the 488 * {@code double} value closest to -3*<i>pi</i>/4.</ul> 489 * 490 * <p>The computed result must be within 2 ulps of the exact result. 491 * Results must be semi-monotonic. 492 * 493 * @param y the ordinate coordinate 494 * @param x the abscissa coordinate 495 * @return the <i>theta</i> component of the point 496 * (<i>r</i>, <i>theta</i>) 497 * in polar coordinates that corresponds to the point 498 * (<i>x</i>, <i>y</i>) in Cartesian coordinates. 499 */ 500 public static double atan2(double y, double x) { 501 return StrictMath.atan2(y, x); // default impl. delegates to StrictMath 502 } 503 504 /** 505 * Returns the value of the first argument raised to the power of the 506 * second argument. Special cases: 507 * 508 * <ul><li>If the second argument is positive or negative zero, then the 509 * result is 1.0. 510 * <li>If the second argument is 1.0, then the result is the same as the 511 * first argument. 512 * <li>If the second argument is NaN, then the result is NaN. 513 * <li>If the first argument is NaN and the second argument is nonzero, 514 * then the result is NaN. 515 * 516 * <li>If 517 * <ul> 518 * <li>the absolute value of the first argument is greater than 1 519 * and the second argument is positive infinity, or 520 * <li>the absolute value of the first argument is less than 1 and 521 * the second argument is negative infinity, 522 * </ul> 523 * then the result is positive infinity. 524 * 525 * <li>If 526 * <ul> 527 * <li>the absolute value of the first argument is greater than 1 and 528 * the second argument is negative infinity, or 529 * <li>the absolute value of the 530 * first argument is less than 1 and the second argument is positive 531 * infinity, 532 * </ul> 533 * then the result is positive zero. 534 * 535 * <li>If the absolute value of the first argument equals 1 and the 536 * second argument is infinite, then the result is NaN. 537 * 538 * <li>If 539 * <ul> 540 * <li>the first argument is positive zero and the second argument 541 * is greater than zero, or 542 * <li>the first argument is positive infinity and the second 543 * argument is less than zero, 544 * </ul> 545 * then the result is positive zero. 546 * 547 * <li>If 548 * <ul> 549 * <li>the first argument is positive zero and the second argument 550 * is less than zero, or 551 * <li>the first argument is positive infinity and the second 552 * argument is greater than zero, 553 * </ul> 554 * then the result is positive infinity. 555 * 556 * <li>If 557 * <ul> 558 * <li>the first argument is negative zero and the second argument 559 * is greater than zero but not a finite odd integer, or 560 * <li>the first argument is negative infinity and the second 561 * argument is less than zero but not a finite odd integer, 562 * </ul> 563 * then the result is positive zero. 564 * 565 * <li>If 566 * <ul> 567 * <li>the first argument is negative zero and the second argument 568 * is a positive finite odd integer, or 569 * <li>the first argument is negative infinity and the second 570 * argument is a negative finite odd integer, 571 * </ul> 572 * then the result is negative zero. 573 * 574 * <li>If 575 * <ul> 576 * <li>the first argument is negative zero and the second argument 577 * is less than zero but not a finite odd integer, or 578 * <li>the first argument is negative infinity and the second 579 * argument is greater than zero but not a finite odd integer, 580 * </ul> 581 * then the result is positive infinity. 582 * 583 * <li>If 584 * <ul> 585 * <li>the first argument is negative zero and the second argument 586 * is a negative finite odd integer, or 587 * <li>the first argument is negative infinity and the second 588 * argument is a positive finite odd integer, 589 * </ul> 590 * then the result is negative infinity. 591 * 592 * <li>If the first argument is finite and less than zero 593 * <ul> 594 * <li> if the second argument is a finite even integer, the 595 * result is equal to the result of raising the absolute value of 596 * the first argument to the power of the second argument 597 * 598 * <li>if the second argument is a finite odd integer, the result 599 * is equal to the negative of the result of raising the absolute 600 * value of the first argument to the power of the second 601 * argument 602 * 603 * <li>if the second argument is finite and not an integer, then 604 * the result is NaN. 605 * </ul> 606 * 607 * <li>If both arguments are integers, then the result is exactly equal 608 * to the mathematical result of raising the first argument to the power 609 * of the second argument if that result can in fact be represented 610 * exactly as a {@code double} value.</ul> 611 * 612 * <p>(In the foregoing descriptions, a floating-point value is 613 * considered to be an integer if and only if it is finite and a 614 * fixed point of the method {@link #ceil ceil} or, 615 * equivalently, a fixed point of the method {@link #floor 616 * floor}. A value is a fixed point of a one-argument 617 * method if and only if the result of applying the method to the 618 * value is equal to the value.) 619 * 620 * <p>The computed result must be within 1 ulp of the exact result. 621 * Results must be semi-monotonic. 622 * 623 * @param a the base. 624 * @param b the exponent. 625 * @return the value {@code a}<sup>{@code b}</sup>. 626 */ 627 public static double pow(double a, double b) { 628 return StrictMath.pow(a, b); // default impl. delegates to StrictMath 629 } 630 631 /** 632 * Returns the closest {@code int} to the argument, with ties 633 * rounding up. 634 * 635 * <p> 636 * Special cases: 637 * <ul><li>If the argument is NaN, the result is 0. 638 * <li>If the argument is negative infinity or any value less than or 639 * equal to the value of {@code Integer.MIN_VALUE}, the result is 640 * equal to the value of {@code Integer.MIN_VALUE}. 641 * <li>If the argument is positive infinity or any value greater than or 642 * equal to the value of {@code Integer.MAX_VALUE}, the result is 643 * equal to the value of {@code Integer.MAX_VALUE}.</ul> 644 * 645 * @param a a floating-point value to be rounded to an integer. 646 * @return the value of the argument rounded to the nearest 647 * {@code int} value. 648 * @see java.lang.Integer#MAX_VALUE 649 * @see java.lang.Integer#MIN_VALUE 650 */ 651 public static int round(float a) { 652 if (a != 0x1.fffffep-2f) // greatest float value less than 0.5 653 return (int)floor(a + 0.5f); 654 else 655 return 0; 656 } 657 658 /** 659 * Returns the closest {@code long} to the argument, with ties 660 * rounding up. 661 * 662 * <p>Special cases: 663 * <ul><li>If the argument is NaN, the result is 0. 664 * <li>If the argument is negative infinity or any value less than or 665 * equal to the value of {@code Long.MIN_VALUE}, the result is 666 * equal to the value of {@code Long.MIN_VALUE}. 667 * <li>If the argument is positive infinity or any value greater than or 668 * equal to the value of {@code Long.MAX_VALUE}, the result is 669 * equal to the value of {@code Long.MAX_VALUE}.</ul> 670 * 671 * @param a a floating-point value to be rounded to a 672 * {@code long}. 673 * @return the value of the argument rounded to the nearest 674 * {@code long} value. 675 * @see java.lang.Long#MAX_VALUE 676 * @see java.lang.Long#MIN_VALUE 677 */ 678 public static long round(double a) { 679 if (a != 0x1.fffffffffffffp-2) // greatest double value less than 0.5 680 return (long)floor(a + 0.5d); 681 else 682 return 0; 683 } 684 685 private static Random randomNumberGenerator; 686 687 private static synchronized Random initRNG() { 688 Random rnd = randomNumberGenerator; 689 return (rnd == null) ? (randomNumberGenerator = new Random()) : rnd; 690 } 691 692 /** 693 * Returns a {@code double} value with a positive sign, greater 694 * than or equal to {@code 0.0} and less than {@code 1.0}. 695 * Returned values are chosen pseudorandomly with (approximately) 696 * uniform distribution from that range. 697 * 698 * <p>When this method is first called, it creates a single new 699 * pseudorandom-number generator, exactly as if by the expression 700 * 701 * <blockquote>{@code new java.util.Random()}</blockquote> 702 * 703 * This new pseudorandom-number generator is used thereafter for 704 * all calls to this method and is used nowhere else. 705 * 706 * <p>This method is properly synchronized to allow correct use by 707 * more than one thread. However, if many threads need to generate 708 * pseudorandom numbers at a great rate, it may reduce contention 709 * for each thread to have its own pseudorandom-number generator. 710 * 711 * @return a pseudorandom {@code double} greater than or equal 712 * to {@code 0.0} and less than {@code 1.0}. 713 * @see Random#nextDouble() 714 */ 715 public static double random() { 716 Random rnd = randomNumberGenerator; 717 if (rnd == null) rnd = initRNG(); 718 return rnd.nextDouble(); 719 } 720 721 /** 722 * Returns the absolute value of an {@code int} value. 723 * If the argument is not negative, the argument is returned. 724 * If the argument is negative, the negation of the argument is returned. 725 * 726 * <p>Note that if the argument is equal to the value of 727 * {@link Integer#MIN_VALUE}, the most negative representable 728 * {@code int} value, the result is that same value, which is 729 * negative. 730 * 731 * @param a the argument whose absolute value is to be determined 732 * @return the absolute value of the argument. 733 */ 734 public static int abs(int a) { 735 return (a < 0) ? -a : a; 736 } 737 738 /** 739 * Returns the absolute value of a {@code long} value. 740 * If the argument is not negative, the argument is returned. 741 * If the argument is negative, the negation of the argument is returned. 742 * 743 * <p>Note that if the argument is equal to the value of 744 * {@link Long#MIN_VALUE}, the most negative representable 745 * {@code long} value, the result is that same value, which 746 * is negative. 747 * 748 * @param a the argument whose absolute value is to be determined 749 * @return the absolute value of the argument. 750 */ 751 public static long abs(long a) { 752 return (a < 0) ? -a : a; 753 } 754 755 /** 756 * Returns the absolute value of a {@code float} value. 757 * If the argument is not negative, the argument is returned. 758 * If the argument is negative, the negation of the argument is returned. 759 * Special cases: 760 * <ul><li>If the argument is positive zero or negative zero, the 761 * result is positive zero. 762 * <li>If the argument is infinite, the result is positive infinity. 763 * <li>If the argument is NaN, the result is NaN.</ul> 764 * In other words, the result is the same as the value of the expression: 765 * <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))} 766 * 767 * @param a the argument whose absolute value is to be determined 768 * @return the absolute value of the argument. 769 */ 770 public static float abs(float a) { 771 return (a <= 0.0F) ? 0.0F - a : a; 772 } 773 774 /** 775 * Returns the absolute value of a {@code double} value. 776 * If the argument is not negative, the argument is returned. 777 * If the argument is negative, the negation of the argument is returned. 778 * Special cases: 779 * <ul><li>If the argument is positive zero or negative zero, the result 780 * is positive zero. 781 * <li>If the argument is infinite, the result is positive infinity. 782 * <li>If the argument is NaN, the result is NaN.</ul> 783 * In other words, the result is the same as the value of the expression: 784 * <p>{@code Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)} 785 * 786 * @param a the argument whose absolute value is to be determined 787 * @return the absolute value of the argument. 788 */ 789 public static double abs(double a) { 790 return (a <= 0.0D) ? 0.0D - a : a; 791 } 792 793 /** 794 * Returns the greater of two {@code int} values. That is, the 795 * result is the argument closer to the value of 796 * {@link Integer#MAX_VALUE}. If the arguments have the same value, 797 * the result is that same value. 798 * 799 * @param a an argument. 800 * @param b another argument. 801 * @return the larger of {@code a} and {@code b}. 802 */ 803 public static int max(int a, int b) { 804 return (a >= b) ? a : b; 805 } 806 807 /** 808 * Returns the greater of two {@code long} values. That is, the 809 * result is the argument closer to the value of 810 * {@link Long#MAX_VALUE}. If the arguments have the same value, 811 * the result is that same value. 812 * 813 * @param a an argument. 814 * @param b another argument. 815 * @return the larger of {@code a} and {@code b}. 816 */ 817 public static long max(long a, long b) { 818 return (a >= b) ? a : b; 819 } 820 821 private static long negativeZeroFloatBits = Float.floatToIntBits(-0.0f); 822 private static long negativeZeroDoubleBits = Double.doubleToLongBits(-0.0d); 823 824 /** 825 * Returns the greater of two {@code float} values. That is, 826 * the result is the argument closer to positive infinity. If the 827 * arguments have the same value, the result is that same 828 * value. If either value is NaN, then the result is NaN. Unlike 829 * the numerical comparison operators, this method considers 830 * negative zero to be strictly smaller than positive zero. If one 831 * argument is positive zero and the other negative zero, the 832 * result is positive zero. 833 * 834 * @param a an argument. 835 * @param b another argument. 836 * @return the larger of {@code a} and {@code b}. 837 */ 838 public static float max(float a, float b) { 839 if (a != a) return a; // a is NaN 840 if ((a == 0.0f) && (b == 0.0f) 841 && (Float.floatToIntBits(a) == negativeZeroFloatBits)) { 842 return b; 843 } 844 return (a >= b) ? a : b; 845 } 846 847 /** 848 * Returns the greater of two {@code double} values. That 849 * is, the result is the argument closer to positive infinity. If 850 * the arguments have the same value, the result is that same 851 * value. If either value is NaN, then the result is NaN. Unlike 852 * the numerical comparison operators, this method considers 853 * negative zero to be strictly smaller than positive zero. If one 854 * argument is positive zero and the other negative zero, the 855 * result is positive zero. 856 * 857 * @param a an argument. 858 * @param b another argument. 859 * @return the larger of {@code a} and {@code b}. 860 */ 861 public static double max(double a, double b) { 862 if (a != a) return a; // a is NaN 863 if ((a == 0.0d) && (b == 0.0d) 864 && (Double.doubleToLongBits(a) == negativeZeroDoubleBits)) { 865 return b; 866 } 867 return (a >= b) ? a : b; 868 } 869 870 /** 871 * Returns the smaller of two {@code int} values. That is, 872 * the result the argument closer to the value of 873 * {@link Integer#MIN_VALUE}. If the arguments have the same 874 * value, the result is that same value. 875 * 876 * @param a an argument. 877 * @param b another argument. 878 * @return the smaller of {@code a} and {@code b}. 879 */ 880 public static int min(int a, int b) { 881 return (a <= b) ? a : b; 882 } 883 884 /** 885 * Returns the smaller of two {@code long} values. That is, 886 * the result is the argument closer to the value of 887 * {@link Long#MIN_VALUE}. If the arguments have the same 888 * value, the result is that same value. 889 * 890 * @param a an argument. 891 * @param b another argument. 892 * @return the smaller of {@code a} and {@code b}. 893 */ 894 public static long min(long a, long b) { 895 return (a <= b) ? a : b; 896 } 897 898 /** 899 * Returns the smaller of two {@code float} values. That is, 900 * the result is the value closer to negative infinity. If the 901 * arguments have the same value, the result is that same 902 * value. If either value is NaN, then the result is NaN. Unlike 903 * the numerical comparison operators, this method considers 904 * negative zero to be strictly smaller than positive zero. If 905 * one argument is positive zero and the other is negative zero, 906 * the result is negative zero. 907 * 908 * @param a an argument. 909 * @param b another argument. 910 * @return the smaller of {@code a} and {@code b}. 911 */ 912 public static float min(float a, float b) { 913 if (a != a) return a; // a is NaN 914 if ((a == 0.0f) && (b == 0.0f) 915 && (Float.floatToIntBits(b) == negativeZeroFloatBits)) { 916 return b; 917 } 918 return (a <= b) ? a : b; 919 } 920 921 /** 922 * Returns the smaller of two {@code double} values. That 923 * is, the result is the value closer to negative infinity. If the 924 * arguments have the same value, the result is that same 925 * value. If either value is NaN, then the result is NaN. Unlike 926 * the numerical comparison operators, this method considers 927 * negative zero to be strictly smaller than positive zero. If one 928 * argument is positive zero and the other is negative zero, the 929 * result is negative zero. 930 * 931 * @param a an argument. 932 * @param b another argument. 933 * @return the smaller of {@code a} and {@code b}. 934 */ 935 public static double min(double a, double b) { 936 if (a != a) return a; // a is NaN 937 if ((a == 0.0d) && (b == 0.0d) 938 && (Double.doubleToLongBits(b) == negativeZeroDoubleBits)) { 939 return b; 940 } 941 return (a <= b) ? a : b; 942 } 943 944 /** 945 * Returns the size of an ulp of the argument. An ulp, unit in 946 * the last place, of a {@code double} value is the positive 947 * distance between this floating-point value and the {@code 948 * double} value next larger in magnitude. Note that for non-NaN 949 * <i>x</i>, <code>ulp(-<i>x</i>) == ulp(<i>x</i>)</code>. 950 * 951 * <p>Special Cases: 952 * <ul> 953 * <li> If the argument is NaN, then the result is NaN. 954 * <li> If the argument is positive or negative infinity, then the 955 * result is positive infinity. 956 * <li> If the argument is positive or negative zero, then the result is 957 * {@code Double.MIN_VALUE}. 958 * <li> If the argument is ±{@code Double.MAX_VALUE}, then 959 * the result is equal to 2<sup>971</sup>. 960 * </ul> 961 * 962 * @param d the floating-point value whose ulp is to be returned 963 * @return the size of an ulp of the argument 964 * @author Joseph D. Darcy 965 * @since 1.5 966 */ 967 public static double ulp(double d) { 968 int exp = getExponent(d); 969 970 switch(exp) { 971 case DoubleConsts.MAX_EXPONENT+1: // NaN or infinity 972 return Math.abs(d); 973 974 case DoubleConsts.MIN_EXPONENT-1: // zero or subnormal 975 return Double.MIN_VALUE; 976 977 default: 978 assert exp <= DoubleConsts.MAX_EXPONENT && exp >= DoubleConsts.MIN_EXPONENT; 979 980 // ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x)) 981 exp = exp - (DoubleConsts.SIGNIFICAND_WIDTH-1); 982 if (exp >= DoubleConsts.MIN_EXPONENT) { 983 return powerOfTwoD(exp); 984 } 985 else { 986 // return a subnormal result; left shift integer 987 // representation of Double.MIN_VALUE appropriate 988 // number of positions 989 return Double.longBitsToDouble(1L << 990 (exp - (DoubleConsts.MIN_EXPONENT - (DoubleConsts.SIGNIFICAND_WIDTH-1)) )); 991 } 992 } 993 } 994 995 /** 996 * Returns the size of an ulp of the argument. An ulp, unit in 997 * the last place, of a {@code float} value is the positive 998 * distance between this floating-point value and the {@code 999 * float} value next larger in magnitude. Note that for non-NaN 1000 * <i>x</i>, <code>ulp(-<i>x</i>) == ulp(<i>x</i>)</code>. 1001 * 1002 * <p>Special Cases: 1003 * <ul> 1004 * <li> If the argument is NaN, then the result is NaN. 1005 * <li> If the argument is positive or negative infinity, then the 1006 * result is positive infinity. 1007 * <li> If the argument is positive or negative zero, then the result is 1008 * {@code Float.MIN_VALUE}. 1009 * <li> If the argument is ±{@code Float.MAX_VALUE}, then 1010 * the result is equal to 2<sup>104</sup>. 1011 * </ul> 1012 * 1013 * @param f the floating-point value whose ulp is to be returned 1014 * @return the size of an ulp of the argument 1015 * @author Joseph D. Darcy 1016 * @since 1.5 1017 */ 1018 public static float ulp(float f) { 1019 int exp = getExponent(f); 1020 1021 switch(exp) { 1022 case FloatConsts.MAX_EXPONENT+1: // NaN or infinity 1023 return Math.abs(f); 1024 1025 case FloatConsts.MIN_EXPONENT-1: // zero or subnormal 1026 return FloatConsts.MIN_VALUE; 1027 1028 default: 1029 assert exp <= FloatConsts.MAX_EXPONENT && exp >= FloatConsts.MIN_EXPONENT; 1030 1031 // ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x)) 1032 exp = exp - (FloatConsts.SIGNIFICAND_WIDTH-1); 1033 if (exp >= FloatConsts.MIN_EXPONENT) { 1034 return powerOfTwoF(exp); 1035 } 1036 else { 1037 // return a subnormal result; left shift integer 1038 // representation of FloatConsts.MIN_VALUE appropriate 1039 // number of positions 1040 return Float.intBitsToFloat(1 << 1041 (exp - (FloatConsts.MIN_EXPONENT - (FloatConsts.SIGNIFICAND_WIDTH-1)) )); 1042 } 1043 } 1044 } 1045 1046 /** 1047 * Returns the signum function of the argument; zero if the argument 1048 * is zero, 1.0 if the argument is greater than zero, -1.0 if the 1049 * argument is less than zero. 1050 * 1051 * <p>Special Cases: 1052 * <ul> 1053 * <li> If the argument is NaN, then the result is NaN. 1054 * <li> If the argument is positive zero or negative zero, then the 1055 * result is the same as the argument. 1056 * </ul> 1057 * 1058 * @param d the floating-point value whose signum is to be returned 1059 * @return the signum function of the argument 1060 * @author Joseph D. Darcy 1061 * @since 1.5 1062 */ 1063 public static double signum(double d) { 1064 return (d == 0.0 || Double.isNaN(d))?d:copySign(1.0, d); 1065 } 1066 1067 /** 1068 * Returns the signum function of the argument; zero if the argument 1069 * is zero, 1.0f if the argument is greater than zero, -1.0f if the 1070 * argument is less than zero. 1071 * 1072 * <p>Special Cases: 1073 * <ul> 1074 * <li> If the argument is NaN, then the result is NaN. 1075 * <li> If the argument is positive zero or negative zero, then the 1076 * result is the same as the argument. 1077 * </ul> 1078 * 1079 * @param f the floating-point value whose signum is to be returned 1080 * @return the signum function of the argument 1081 * @author Joseph D. Darcy 1082 * @since 1.5 1083 */ 1084 public static float signum(float f) { 1085 return (f == 0.0f || Float.isNaN(f))?f:copySign(1.0f, f); 1086 } 1087 1088 /** 1089 * Returns the hyperbolic sine of a {@code double} value. 1090 * The hyperbolic sine of <i>x</i> is defined to be 1091 * (<i>e<sup>x</sup> - e<sup>-x</sup></i>)/2 1092 * where <i>e</i> is {@linkplain Math#E Euler's number}. 1093 * 1094 * <p>Special cases: 1095 * <ul> 1096 * 1097 * <li>If the argument is NaN, then the result is NaN. 1098 * 1099 * <li>If the argument is infinite, then the result is an infinity 1100 * with the same sign as the argument. 1101 * 1102 * <li>If the argument is zero, then the result is a zero with the 1103 * same sign as the argument. 1104 * 1105 * </ul> 1106 * 1107 * <p>The computed result must be within 2.5 ulps of the exact result. 1108 * 1109 * @param x The number whose hyperbolic sine is to be returned. 1110 * @return The hyperbolic sine of {@code x}. 1111 * @since 1.5 1112 */ 1113 public static double sinh(double x) { 1114 return StrictMath.sinh(x); 1115 } 1116 1117 /** 1118 * Returns the hyperbolic cosine of a {@code double} value. 1119 * The hyperbolic cosine of <i>x</i> is defined to be 1120 * (<i>e<sup>x</sup> + e<sup>-x</sup></i>)/2 1121 * where <i>e</i> is {@linkplain Math#E Euler's number}. 1122 * 1123 * <p>Special cases: 1124 * <ul> 1125 * 1126 * <li>If the argument is NaN, then the result is NaN. 1127 * 1128 * <li>If the argument is infinite, then the result is positive 1129 * infinity. 1130 * 1131 * <li>If the argument is zero, then the result is {@code 1.0}. 1132 * 1133 * </ul> 1134 * 1135 * <p>The computed result must be within 2.5 ulps of the exact result. 1136 * 1137 * @param x The number whose hyperbolic cosine is to be returned. 1138 * @return The hyperbolic cosine of {@code x}. 1139 * @since 1.5 1140 */ 1141 public static double cosh(double x) { 1142 return StrictMath.cosh(x); 1143 } 1144 1145 /** 1146 * Returns the hyperbolic tangent of a {@code double} value. 1147 * The hyperbolic tangent of <i>x</i> is defined to be 1148 * (<i>e<sup>x</sup> - e<sup>-x</sup></i>)/(<i>e<sup>x</sup> + e<sup>-x</sup></i>), 1149 * in other words, {@linkplain Math#sinh 1150 * sinh(<i>x</i>)}/{@linkplain Math#cosh cosh(<i>x</i>)}. Note 1151 * that the absolute value of the exact tanh is always less than 1152 * 1. 1153 * 1154 * <p>Special cases: 1155 * <ul> 1156 * 1157 * <li>If the argument is NaN, then the result is NaN. 1158 * 1159 * <li>If the argument is zero, then the result is a zero with the 1160 * same sign as the argument. 1161 * 1162 * <li>If the argument is positive infinity, then the result is 1163 * {@code +1.0}. 1164 * 1165 * <li>If the argument is negative infinity, then the result is 1166 * {@code -1.0}. 1167 * 1168 * </ul> 1169 * 1170 * <p>The computed result must be within 2.5 ulps of the exact result. 1171 * The result of {@code tanh} for any finite input must have 1172 * an absolute value less than or equal to 1. Note that once the 1173 * exact result of tanh is within 1/2 of an ulp of the limit value 1174 * of ±1, correctly signed ±{@code 1.0} should 1175 * be returned. 1176 * 1177 * @param x The number whose hyperbolic tangent is to be returned. 1178 * @return The hyperbolic tangent of {@code x}. 1179 * @since 1.5 1180 */ 1181 public static double tanh(double x) { 1182 return StrictMath.tanh(x); 1183 } 1184 1185 /** 1186 * Returns sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) 1187 * without intermediate overflow or underflow. 1188 * 1189 * <p>Special cases: 1190 * <ul> 1191 * 1192 * <li> If either argument is infinite, then the result 1193 * is positive infinity. 1194 * 1195 * <li> If either argument is NaN and neither argument is infinite, 1196 * then the result is NaN. 1197 * 1198 * </ul> 1199 * 1200 * <p>The computed result must be within 1 ulp of the exact 1201 * result. If one parameter is held constant, the results must be 1202 * semi-monotonic in the other parameter. 1203 * 1204 * @param x a value 1205 * @param y a value 1206 * @return sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) 1207 * without intermediate overflow or underflow 1208 * @since 1.5 1209 */ 1210 public static double hypot(double x, double y) { 1211 return StrictMath.hypot(x, y); 1212 } 1213 1214 /** 1215 * Returns <i>e</i><sup>x</sup> -1. Note that for values of 1216 * <i>x</i> near 0, the exact sum of 1217 * {@code expm1(x)} + 1 is much closer to the true 1218 * result of <i>e</i><sup>x</sup> than {@code exp(x)}. 1219 * 1220 * <p>Special cases: 1221 * <ul> 1222 * <li>If the argument is NaN, the result is NaN. 1223 * 1224 * <li>If the argument is positive infinity, then the result is 1225 * positive infinity. 1226 * 1227 * <li>If the argument is negative infinity, then the result is 1228 * -1.0. 1229 * 1230 * <li>If the argument is zero, then the result is a zero with the 1231 * same sign as the argument. 1232 * 1233 * </ul> 1234 * 1235 * <p>The computed result must be within 1 ulp of the exact result. 1236 * Results must be semi-monotonic. The result of 1237 * {@code expm1} for any finite input must be greater than or 1238 * equal to {@code -1.0}. Note that once the exact result of 1239 * <i>e</i><sup>{@code x}</sup> - 1 is within 1/2 1240 * ulp of the limit value -1, {@code -1.0} should be 1241 * returned. 1242 * 1243 * @param x the exponent to raise <i>e</i> to in the computation of 1244 * <i>e</i><sup>{@code x}</sup> -1. 1245 * @return the value <i>e</i><sup>{@code x}</sup> - 1. 1246 * @since 1.5 1247 */ 1248 public static double expm1(double x) { 1249 return StrictMath.expm1(x); 1250 } 1251 1252 /** 1253 * Returns the natural logarithm of the sum of the argument and 1. 1254 * Note that for small values {@code x}, the result of 1255 * {@code log1p(x)} is much closer to the true result of ln(1 1256 * + {@code x}) than the floating-point evaluation of 1257 * {@code log(1.0+x)}. 1258 * 1259 * <p>Special cases: 1260 * 1261 * <ul> 1262 * 1263 * <li>If the argument is NaN or less than -1, then the result is 1264 * NaN. 1265 * 1266 * <li>If the argument is positive infinity, then the result is 1267 * positive infinity. 1268 * 1269 * <li>If the argument is negative one, then the result is 1270 * negative infinity. 1271 * 1272 * <li>If the argument is zero, then the result is a zero with the 1273 * same sign as the argument. 1274 * 1275 * </ul> 1276 * 1277 * <p>The computed result must be within 1 ulp of the exact result. 1278 * Results must be semi-monotonic. 1279 * 1280 * @param x a value 1281 * @return the value ln({@code x} + 1), the natural 1282 * log of {@code x} + 1 1283 * @since 1.5 1284 */ 1285 public static double log1p(double x) { 1286 return StrictMath.log1p(x); 1287 } 1288 1289 /** 1290 * Returns the first floating-point argument with the sign of the 1291 * second floating-point argument. Note that unlike the {@link 1292 * StrictMath#copySign(double, double) StrictMath.copySign} 1293 * method, this method does not require NaN {@code sign} 1294 * arguments to be treated as positive values; implementations are 1295 * permitted to treat some NaN arguments as positive and other NaN 1296 * arguments as negative to allow greater performance. 1297 * 1298 * @param magnitude the parameter providing the magnitude of the result 1299 * @param sign the parameter providing the sign of the result 1300 * @return a value with the magnitude of {@code magnitude} 1301 * and the sign of {@code sign}. 1302 * @since 1.6 1303 */ 1304 public static double copySign(double magnitude, double sign) { 1305 return Double.longBitsToDouble((Double.doubleToRawLongBits(sign) & 1306 (DoubleConsts.SIGN_BIT_MASK)) | 1307 (Double.doubleToRawLongBits(magnitude) & 1308 (DoubleConsts.EXP_BIT_MASK | 1309 DoubleConsts.SIGNIF_BIT_MASK))); 1310 } 1311 1312 /** 1313 * Returns the first floating-point argument with the sign of the 1314 * second floating-point argument. Note that unlike the {@link 1315 * StrictMath#copySign(float, float) StrictMath.copySign} 1316 * method, this method does not require NaN {@code sign} 1317 * arguments to be treated as positive values; implementations are 1318 * permitted to treat some NaN arguments as positive and other NaN 1319 * arguments as negative to allow greater performance. 1320 * 1321 * @param magnitude the parameter providing the magnitude of the result 1322 * @param sign the parameter providing the sign of the result 1323 * @return a value with the magnitude of {@code magnitude} 1324 * and the sign of {@code sign}. 1325 * @since 1.6 1326 */ 1327 public static float copySign(float magnitude, float sign) { 1328 return Float.intBitsToFloat((Float.floatToRawIntBits(sign) & 1329 (FloatConsts.SIGN_BIT_MASK)) | 1330 (Float.floatToRawIntBits(magnitude) & 1331 (FloatConsts.EXP_BIT_MASK | 1332 FloatConsts.SIGNIF_BIT_MASK))); 1333 } 1334 1335 /** 1336 * Returns the unbiased exponent used in the representation of a 1337 * {@code float}. Special cases: 1338 * 1339 * <ul> 1340 * <li>If the argument is NaN or infinite, then the result is 1341 * {@link Float#MAX_EXPONENT} + 1. 1342 * <li>If the argument is zero or subnormal, then the result is 1343 * {@link Float#MIN_EXPONENT} -1. 1344 * </ul> 1345 * @param f a {@code float} value 1346 * @return the unbiased exponent of the argument 1347 * @since 1.6 1348 */ 1349 public static int getExponent(float f) { 1350 /* 1351 * Bitwise convert f to integer, mask out exponent bits, shift 1352 * to the right and then subtract out float's bias adjust to 1353 * get true exponent value 1354 */ 1355 return ((Float.floatToRawIntBits(f) & FloatConsts.EXP_BIT_MASK) >> 1356 (FloatConsts.SIGNIFICAND_WIDTH - 1)) - FloatConsts.EXP_BIAS; 1357 } 1358 1359 /** 1360 * Returns the unbiased exponent used in the representation of a 1361 * {@code double}. Special cases: 1362 * 1363 * <ul> 1364 * <li>If the argument is NaN or infinite, then the result is 1365 * {@link Double#MAX_EXPONENT} + 1. 1366 * <li>If the argument is zero or subnormal, then the result is 1367 * {@link Double#MIN_EXPONENT} -1. 1368 * </ul> 1369 * @param d a {@code double} value 1370 * @return the unbiased exponent of the argument 1371 * @since 1.6 1372 */ 1373 public static int getExponent(double d) { 1374 /* 1375 * Bitwise convert d to long, mask out exponent bits, shift 1376 * to the right and then subtract out double's bias adjust to 1377 * get true exponent value. 1378 */ 1379 return (int)(((Double.doubleToRawLongBits(d) & DoubleConsts.EXP_BIT_MASK) >> 1380 (DoubleConsts.SIGNIFICAND_WIDTH - 1)) - DoubleConsts.EXP_BIAS); 1381 } 1382 1383 /** 1384 * Returns the floating-point number adjacent to the first 1385 * argument in the direction of the second argument. If both 1386 * arguments compare as equal the second argument is returned. 1387 * 1388 * <p> 1389 * Special cases: 1390 * <ul> 1391 * <li> If either argument is a NaN, then NaN is returned. 1392 * 1393 * <li> If both arguments are signed zeros, {@code direction} 1394 * is returned unchanged (as implied by the requirement of 1395 * returning the second argument if the arguments compare as 1396 * equal). 1397 * 1398 * <li> If {@code start} is 1399 * ±{@link Double#MIN_VALUE} and {@code direction} 1400 * has a value such that the result should have a smaller 1401 * magnitude, then a zero with the same sign as {@code start} 1402 * is returned. 1403 * 1404 * <li> If {@code start} is infinite and 1405 * {@code direction} has a value such that the result should 1406 * have a smaller magnitude, {@link Double#MAX_VALUE} with the 1407 * same sign as {@code start} is returned. 1408 * 1409 * <li> If {@code start} is equal to ± 1410 * {@link Double#MAX_VALUE} and {@code direction} has a 1411 * value such that the result should have a larger magnitude, an 1412 * infinity with same sign as {@code start} is returned. 1413 * </ul> 1414 * 1415 * @param start starting floating-point value 1416 * @param direction value indicating which of 1417 * {@code start}'s neighbors or {@code start} should 1418 * be returned 1419 * @return The floating-point number adjacent to {@code start} in the 1420 * direction of {@code direction}. 1421 * @since 1.6 1422 */ 1423 public static double nextAfter(double start, double direction) { 1424 /* 1425 * The cases: 1426 * 1427 * nextAfter(+infinity, 0) == MAX_VALUE 1428 * nextAfter(+infinity, +infinity) == +infinity 1429 * nextAfter(-infinity, 0) == -MAX_VALUE 1430 * nextAfter(-infinity, -infinity) == -infinity 1431 * 1432 * are naturally handled without any additional testing 1433 */ 1434 1435 // First check for NaN values 1436 if (Double.isNaN(start) || Double.isNaN(direction)) { 1437 // return a NaN derived from the input NaN(s) 1438 return start + direction; 1439 } else if (start == direction) { 1440 return direction; 1441 } else { // start > direction or start < direction 1442 // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0) 1443 // then bitwise convert start to integer. 1444 long transducer = Double.doubleToRawLongBits(start + 0.0d); 1445 1446 /* 1447 * IEEE 754 floating-point numbers are lexicographically 1448 * ordered if treated as signed- magnitude integers . 1449 * Since Java's integers are two's complement, 1450 * incrementing" the two's complement representation of a 1451 * logically negative floating-point value *decrements* 1452 * the signed-magnitude representation. Therefore, when 1453 * the integer representation of a floating-point values 1454 * is less than zero, the adjustment to the representation 1455 * is in the opposite direction than would be expected at 1456 * first . 1457 */ 1458 if (direction > start) { // Calculate next greater value 1459 transducer = transducer + (transducer >= 0L ? 1L:-1L); 1460 } else { // Calculate next lesser value 1461 assert direction < start; 1462 if (transducer > 0L) 1463 --transducer; 1464 else 1465 if (transducer < 0L ) 1466 ++transducer; 1467 /* 1468 * transducer==0, the result is -MIN_VALUE 1469 * 1470 * The transition from zero (implicitly 1471 * positive) to the smallest negative 1472 * signed magnitude value must be done 1473 * explicitly. 1474 */ 1475 else 1476 transducer = DoubleConsts.SIGN_BIT_MASK | 1L; 1477 } 1478 1479 return Double.longBitsToDouble(transducer); 1480 } 1481 } 1482 1483 /** 1484 * Returns the floating-point number adjacent to the first 1485 * argument in the direction of the second argument. If both 1486 * arguments compare as equal a value equivalent to the second argument 1487 * is returned. 1488 * 1489 * <p> 1490 * Special cases: 1491 * <ul> 1492 * <li> If either argument is a NaN, then NaN is returned. 1493 * 1494 * <li> If both arguments are signed zeros, a value equivalent 1495 * to {@code direction} is returned. 1496 * 1497 * <li> If {@code start} is 1498 * ±{@link Float#MIN_VALUE} and {@code direction} 1499 * has a value such that the result should have a smaller 1500 * magnitude, then a zero with the same sign as {@code start} 1501 * is returned. 1502 * 1503 * <li> If {@code start} is infinite and 1504 * {@code direction} has a value such that the result should 1505 * have a smaller magnitude, {@link Float#MAX_VALUE} with the 1506 * same sign as {@code start} is returned. 1507 * 1508 * <li> If {@code start} is equal to ± 1509 * {@link Float#MAX_VALUE} and {@code direction} has a 1510 * value such that the result should have a larger magnitude, an 1511 * infinity with same sign as {@code start} is returned. 1512 * </ul> 1513 * 1514 * @param start starting floating-point value 1515 * @param direction value indicating which of 1516 * {@code start}'s neighbors or {@code start} should 1517 * be returned 1518 * @return The floating-point number adjacent to {@code start} in the 1519 * direction of {@code direction}. 1520 * @since 1.6 1521 */ 1522 public static float nextAfter(float start, double direction) { 1523 /* 1524 * The cases: 1525 * 1526 * nextAfter(+infinity, 0) == MAX_VALUE 1527 * nextAfter(+infinity, +infinity) == +infinity 1528 * nextAfter(-infinity, 0) == -MAX_VALUE 1529 * nextAfter(-infinity, -infinity) == -infinity 1530 * 1531 * are naturally handled without any additional testing 1532 */ 1533 1534 // First check for NaN values 1535 if (Float.isNaN(start) || Double.isNaN(direction)) { 1536 // return a NaN derived from the input NaN(s) 1537 return start + (float)direction; 1538 } else if (start == direction) { 1539 return (float)direction; 1540 } else { // start > direction or start < direction 1541 // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0) 1542 // then bitwise convert start to integer. 1543 int transducer = Float.floatToRawIntBits(start + 0.0f); 1544 1545 /* 1546 * IEEE 754 floating-point numbers are lexicographically 1547 * ordered if treated as signed- magnitude integers . 1548 * Since Java's integers are two's complement, 1549 * incrementing" the two's complement representation of a 1550 * logically negative floating-point value *decrements* 1551 * the signed-magnitude representation. Therefore, when 1552 * the integer representation of a floating-point values 1553 * is less than zero, the adjustment to the representation 1554 * is in the opposite direction than would be expected at 1555 * first. 1556 */ 1557 if (direction > start) {// Calculate next greater value 1558 transducer = transducer + (transducer >= 0 ? 1:-1); 1559 } else { // Calculate next lesser value 1560 assert direction < start; 1561 if (transducer > 0) 1562 --transducer; 1563 else 1564 if (transducer < 0 ) 1565 ++transducer; 1566 /* 1567 * transducer==0, the result is -MIN_VALUE 1568 * 1569 * The transition from zero (implicitly 1570 * positive) to the smallest negative 1571 * signed magnitude value must be done 1572 * explicitly. 1573 */ 1574 else 1575 transducer = FloatConsts.SIGN_BIT_MASK | 1; 1576 } 1577 1578 return Float.intBitsToFloat(transducer); 1579 } 1580 } 1581 1582 /** 1583 * Returns the floating-point value adjacent to {@code d} in 1584 * the direction of positive infinity. This method is 1585 * semantically equivalent to {@code nextAfter(d, 1586 * Double.POSITIVE_INFINITY)}; however, a {@code nextUp} 1587 * implementation may run faster than its equivalent 1588 * {@code nextAfter} call. 1589 * 1590 * <p>Special Cases: 1591 * <ul> 1592 * <li> If the argument is NaN, the result is NaN. 1593 * 1594 * <li> If the argument is positive infinity, the result is 1595 * positive infinity. 1596 * 1597 * <li> If the argument is zero, the result is 1598 * {@link Double#MIN_VALUE} 1599 * 1600 * </ul> 1601 * 1602 * @param d starting floating-point value 1603 * @return The adjacent floating-point value closer to positive 1604 * infinity. 1605 * @since 1.6 1606 */ 1607 public static double nextUp(double d) { 1608 if( Double.isNaN(d) || d == Double.POSITIVE_INFINITY) 1609 return d; 1610 else { 1611 d += 0.0d; 1612 return Double.longBitsToDouble(Double.doubleToRawLongBits(d) + 1613 ((d >= 0.0d)?+1L:-1L)); 1614 } 1615 } 1616 1617 /** 1618 * Returns the floating-point value adjacent to {@code f} in 1619 * the direction of positive infinity. This method is 1620 * semantically equivalent to {@code nextAfter(f, 1621 * Float.POSITIVE_INFINITY)}; however, a {@code nextUp} 1622 * implementation may run faster than its equivalent 1623 * {@code nextAfter} call. 1624 * 1625 * <p>Special Cases: 1626 * <ul> 1627 * <li> If the argument is NaN, the result is NaN. 1628 * 1629 * <li> If the argument is positive infinity, the result is 1630 * positive infinity. 1631 * 1632 * <li> If the argument is zero, the result is 1633 * {@link Float#MIN_VALUE} 1634 * 1635 * </ul> 1636 * 1637 * @param f starting floating-point value 1638 * @return The adjacent floating-point value closer to positive 1639 * infinity. 1640 * @since 1.6 1641 */ 1642 public static float nextUp(float f) { 1643 if( Float.isNaN(f) || f == FloatConsts.POSITIVE_INFINITY) 1644 return f; 1645 else { 1646 f += 0.0f; 1647 return Float.intBitsToFloat(Float.floatToRawIntBits(f) + 1648 ((f >= 0.0f)?+1:-1)); 1649 } 1650 } 1651 1652 /** 1653 * Returns the floating-point value adjacent to {@code d} in 1654 * the direction of negative infinity. This method is 1655 * semantically equivalent to {@code nextAfter(d, 1656 * Double.NEGATIVE_INFINITY)}; however, a 1657 * {@code nextDown} implementation may run faster than its 1658 * equivalent {@code nextAfter} call. 1659 * 1660 * <p>Special Cases: 1661 * <ul> 1662 * <li> If the argument is NaN, the result is NaN. 1663 * 1664 * <li> If the argument is negative infinity, the result is 1665 * negative infinity. 1666 * 1667 * <li> If the argument is zero, the result is 1668 * {@code -Double.MIN_VALUE} 1669 * 1670 * </ul> 1671 * 1672 * @param d starting floating-point value 1673 * @return The adjacent floating-point value closer to negative 1674 * infinity. 1675 * @since 1.8 1676 */ 1677 public static double nextDown(double d) { 1678 if (Double.isNaN(d) || d == Double.NEGATIVE_INFINITY) 1679 return d; 1680 else { 1681 if (d == 0.0) 1682 return -Double.MIN_VALUE; 1683 else 1684 return Double.longBitsToDouble(Double.doubleToRawLongBits(d) + 1685 ((d > 0.0d)?-1L:+1L)); 1686 } 1687 } 1688 1689 /** 1690 * Returns the floating-point value adjacent to {@code f} in 1691 * the direction of negative infinity. This method is 1692 * semantically equivalent to {@code nextAfter(f, 1693 * Float.NEGATIVE_INFINITY)}; however, a 1694 * {@code nextDown} implementation may run faster than its 1695 * equivalent {@code nextAfter} call. 1696 * 1697 * <p>Special Cases: 1698 * <ul> 1699 * <li> If the argument is NaN, the result is NaN. 1700 * 1701 * <li> If the argument is negative infinity, the result is 1702 * negative infinity. 1703 * 1704 * <li> If the argument is zero, the result is 1705 * {@code -Float.MIN_VALUE} 1706 * 1707 * </ul> 1708 * 1709 * @param f starting floating-point value 1710 * @return The adjacent floating-point value closer to negative 1711 * infinity. 1712 * @since 1.8 1713 */ 1714 public static double nextDown(float f) { 1715 if (Float.isNaN(f) || f == Float.NEGATIVE_INFINITY) 1716 return f; 1717 else { 1718 if (f == 0.0f) 1719 return -Float.MIN_VALUE; 1720 else 1721 return Float.intBitsToFloat(Float.floatToRawIntBits(f) + 1722 ((f > 0.0f)?-1:+1)); 1723 } 1724 } 1725 1726 /** 1727 * Return {@code d} × 1728 * 2<sup>{@code scaleFactor}</sup> rounded as if performed 1729 * by a single correctly rounded floating-point multiply to a 1730 * member of the double value set. See the Java 1731 * Language Specification for a discussion of floating-point 1732 * value sets. If the exponent of the result is between {@link 1733 * Double#MIN_EXPONENT} and {@link Double#MAX_EXPONENT}, the 1734 * answer is calculated exactly. If the exponent of the result 1735 * would be larger than {@code Double.MAX_EXPONENT}, an 1736 * infinity is returned. Note that if the result is subnormal, 1737 * precision may be lost; that is, when {@code scalb(x, n)} 1738 * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal 1739 * <i>x</i>. When the result is non-NaN, the result has the same 1740 * sign as {@code d}. 1741 * 1742 * <p>Special cases: 1743 * <ul> 1744 * <li> If the first argument is NaN, NaN is returned. 1745 * <li> If the first argument is infinite, then an infinity of the 1746 * same sign is returned. 1747 * <li> If the first argument is zero, then a zero of the same 1748 * sign is returned. 1749 * </ul> 1750 * 1751 * @param d number to be scaled by a power of two. 1752 * @param scaleFactor power of 2 used to scale {@code d} 1753 * @return {@code d} × 2<sup>{@code scaleFactor}</sup> 1754 * @since 1.6 1755 */ 1756 public static double scalb(double d, int scaleFactor) { 1757 /* 1758 * This method does not need to be declared strictfp to 1759 * compute the same correct result on all platforms. When 1760 * scaling up, it does not matter what order the 1761 * multiply-store operations are done; the result will be 1762 * finite or overflow regardless of the operation ordering. 1763 * However, to get the correct result when scaling down, a 1764 * particular ordering must be used. 1765 * 1766 * When scaling down, the multiply-store operations are 1767 * sequenced so that it is not possible for two consecutive 1768 * multiply-stores to return subnormal results. If one 1769 * multiply-store result is subnormal, the next multiply will 1770 * round it away to zero. This is done by first multiplying 1771 * by 2 ^ (scaleFactor % n) and then multiplying several 1772 * times by by 2^n as needed where n is the exponent of number 1773 * that is a covenient power of two. In this way, at most one 1774 * real rounding error occurs. If the double value set is 1775 * being used exclusively, the rounding will occur on a 1776 * multiply. If the double-extended-exponent value set is 1777 * being used, the products will (perhaps) be exact but the 1778 * stores to d are guaranteed to round to the double value 1779 * set. 1780 * 1781 * It is _not_ a valid implementation to first multiply d by 1782 * 2^MIN_EXPONENT and then by 2 ^ (scaleFactor % 1783 * MIN_EXPONENT) since even in a strictfp program double 1784 * rounding on underflow could occur; e.g. if the scaleFactor 1785 * argument was (MIN_EXPONENT - n) and the exponent of d was a 1786 * little less than -(MIN_EXPONENT - n), meaning the final 1787 * result would be subnormal. 1788 * 1789 * Since exact reproducibility of this method can be achieved 1790 * without any undue performance burden, there is no 1791 * compelling reason to allow double rounding on underflow in 1792 * scalb. 1793 */ 1794 1795 // magnitude of a power of two so large that scaling a finite 1796 // nonzero value by it would be guaranteed to over or 1797 // underflow; due to rounding, scaling down takes takes an 1798 // additional power of two which is reflected here 1799 final int MAX_SCALE = DoubleConsts.MAX_EXPONENT + -DoubleConsts.MIN_EXPONENT + 1800 DoubleConsts.SIGNIFICAND_WIDTH + 1; 1801 int exp_adjust = 0; 1802 int scale_increment = 0; 1803 double exp_delta = Double.NaN; 1804 1805 // Make sure scaling factor is in a reasonable range 1806 1807 if(scaleFactor < 0) { 1808 scaleFactor = Math.max(scaleFactor, -MAX_SCALE); 1809 scale_increment = -512; 1810 exp_delta = twoToTheDoubleScaleDown; 1811 } 1812 else { 1813 scaleFactor = Math.min(scaleFactor, MAX_SCALE); 1814 scale_increment = 512; 1815 exp_delta = twoToTheDoubleScaleUp; 1816 } 1817 1818 // Calculate (scaleFactor % +/-512), 512 = 2^9, using 1819 // technique from "Hacker's Delight" section 10-2. 1820 int t = (scaleFactor >> 9-1) >>> 32 - 9; 1821 exp_adjust = ((scaleFactor + t) & (512 -1)) - t; 1822 1823 d *= powerOfTwoD(exp_adjust); 1824 scaleFactor -= exp_adjust; 1825 1826 while(scaleFactor != 0) { 1827 d *= exp_delta; 1828 scaleFactor -= scale_increment; 1829 } 1830 return d; 1831 } 1832 1833 /** 1834 * Return {@code f} × 1835 * 2<sup>{@code scaleFactor}</sup> rounded as if performed 1836 * by a single correctly rounded floating-point multiply to a 1837 * member of the float value set. See the Java 1838 * Language Specification for a discussion of floating-point 1839 * value sets. If the exponent of the result is between {@link 1840 * Float#MIN_EXPONENT} and {@link Float#MAX_EXPONENT}, the 1841 * answer is calculated exactly. If the exponent of the result 1842 * would be larger than {@code Float.MAX_EXPONENT}, an 1843 * infinity is returned. Note that if the result is subnormal, 1844 * precision may be lost; that is, when {@code scalb(x, n)} 1845 * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal 1846 * <i>x</i>. When the result is non-NaN, the result has the same 1847 * sign as {@code f}. 1848 * 1849 * <p>Special cases: 1850 * <ul> 1851 * <li> If the first argument is NaN, NaN is returned. 1852 * <li> If the first argument is infinite, then an infinity of the 1853 * same sign is returned. 1854 * <li> If the first argument is zero, then a zero of the same 1855 * sign is returned. 1856 * </ul> 1857 * 1858 * @param f number to be scaled by a power of two. 1859 * @param scaleFactor power of 2 used to scale {@code f} 1860 * @return {@code f} × 2<sup>{@code scaleFactor}</sup> 1861 * @since 1.6 1862 */ 1863 public static float scalb(float f, int scaleFactor) { 1864 // magnitude of a power of two so large that scaling a finite 1865 // nonzero value by it would be guaranteed to over or 1866 // underflow; due to rounding, scaling down takes takes an 1867 // additional power of two which is reflected here 1868 final int MAX_SCALE = FloatConsts.MAX_EXPONENT + -FloatConsts.MIN_EXPONENT + 1869 FloatConsts.SIGNIFICAND_WIDTH + 1; 1870 1871 // Make sure scaling factor is in a reasonable range 1872 scaleFactor = Math.max(Math.min(scaleFactor, MAX_SCALE), -MAX_SCALE); 1873 1874 /* 1875 * Since + MAX_SCALE for float fits well within the double 1876 * exponent range and + float -> double conversion is exact 1877 * the multiplication below will be exact. Therefore, the 1878 * rounding that occurs when the double product is cast to 1879 * float will be the correctly rounded float result. Since 1880 * all operations other than the final multiply will be exact, 1881 * it is not necessary to declare this method strictfp. 1882 */ 1883 return (float)((double)f*powerOfTwoD(scaleFactor)); 1884 } 1885 1886 // Constants used in scalb 1887 static double twoToTheDoubleScaleUp = powerOfTwoD(512); 1888 static double twoToTheDoubleScaleDown = powerOfTwoD(-512); 1889 1890 /** 1891 * Returns a floating-point power of two in the normal range. 1892 */ 1893 static double powerOfTwoD(int n) { 1894 assert(n >= DoubleConsts.MIN_EXPONENT && n <= DoubleConsts.MAX_EXPONENT); 1895 return Double.longBitsToDouble((((long)n + (long)DoubleConsts.EXP_BIAS) << 1896 (DoubleConsts.SIGNIFICAND_WIDTH-1)) 1897 & DoubleConsts.EXP_BIT_MASK); 1898 } 1899 1900 /** 1901 * Returns a floating-point power of two in the normal range. 1902 */ 1903 public static float powerOfTwoF(int n) { 1904 assert(n >= FloatConsts.MIN_EXPONENT && n <= FloatConsts.MAX_EXPONENT); 1905 return Float.intBitsToFloat(((n + FloatConsts.EXP_BIAS) << 1906 (FloatConsts.SIGNIFICAND_WIDTH-1)) 1907 & FloatConsts.EXP_BIT_MASK); 1908 } 1909 }