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