/** *Returnsthecorrectlyroundedpositivesquarerootofa *{@codedouble}value. *Specialcases: *<ul><li>IftheargumentisNaNorlessthanzero,thentheresult *isNaN. *<li>Iftheargumentispositiveinfinity,thentheresultispositive *infinity. *<li>Iftheargumentispositivezeroornegativezero,thenthe *resultisthesameastheargument.</ul> *Otherwise,theresultisthe{@codedouble}valueclosestto *thetruemathematicalsquarerootoftheargumentvalue. * *@apiNote *ThismethodcorrespondstothesquareRootoperationdefinedin *IEEE754. * *@paramaavalue. *@returnthepositivesquarerootof{@codea}. *IftheargumentisNaNorlessthanzero,theresultisNaN.
*/
@IntrinsicCandidate publicstaticdouble sqrt(double a) { return StrictMath.sqrt(a); // default impl. delegates to StrictMath // Note that hardware sqrt instructions // frequently can be directly used by JITs // and should be much faster than doing // Math.sqrt in software.
}
/** *Returnstheclosest{@codeint}totheargument,withties *roundingtopositiveinfinity. * *<p> *Specialcases: *<ul><li>IftheargumentisNaN,theresultis0. *<li>Iftheargumentisnegativeinfinityoranyvaluelessthanor *equaltothevalueof{@codeInteger.MIN_VALUE},theresultis *equaltothevalueof{@codeInteger.MIN_VALUE}. *<li>Iftheargumentispositiveinfinityoranyvaluegreaterthanor *equaltothevalueof{@codeInteger.MAX_VALUE},theresultis *equaltothevalueof{@codeInteger.MAX_VALUE}.</ul> * *@paramaafloating-pointvaluetoberoundedtoaninteger. *@returnthevalueoftheargumentroundedtothenearest *{@codeint}value. *@seejava.lang.Integer#MAX_VALUE *@seejava.lang.Integer#MIN_VALUE
*/
@IntrinsicCandidate publicstaticint round(float a) { int intBits = Float.floatToRawIntBits(a); int biasedExp = (intBits & FloatConsts.EXP_BIT_MASK)
>> (FloatConsts.SIGNIFICAND_WIDTH - 1); int shift = (FloatConsts.SIGNIFICAND_WIDTH - 2
+ FloatConsts.EXP_BIAS) - biasedExp; if ((shift & -32) == 0) { // shift >= 0 && shift < 32 // a is a finite number such that pow(2,-32) <= ulp(a) < 1 int r = ((intBits & FloatConsts.SIGNIF_BIT_MASK)
| (FloatConsts.SIGNIF_BIT_MASK + 1)); if (intBits < 0) {
r = -r;
} // In the comments below each Java expression evaluates to the value // the corresponding mathematical expression: // (r) evaluates to a / ulp(a) // (r >> shift) evaluates to floor(a * 2) // ((r >> shift) + 1) evaluates to floor((a + 1/2) * 2) // (((r >> shift) + 1) >> 1) evaluates to floor(a + 1/2) return ((r >> shift) + 1) >> 1;
} else { // a is either // - a finite number with abs(a) < exp(2,FloatConsts.SIGNIFICAND_WIDTH-32) < 1/2 // - a finite number with ulp(a) >= 1 and hence a is a mathematical integer // - an infinity or NaN return (int) a;
}
}
/** *Returnstheclosest{@codelong}totheargument,withties *roundingtopositiveinfinity. * *<p>Specialcases: *<ul><li>IftheargumentisNaN,theresultis0. *<li>Iftheargumentisnegativeinfinityoranyvaluelessthanor *equaltothevalueof{@codeLong.MIN_VALUE},theresultis *equaltothevalueof{@codeLong.MIN_VALUE}. *<li>Iftheargumentispositiveinfinityoranyvaluegreaterthanor *equaltothevalueof{@codeLong.MAX_VALUE},theresultis *equaltothevalueof{@codeLong.MAX_VALUE}.</ul> * *@paramaafloating-pointvaluetoberoundedtoa *{@codelong}. *@returnthevalueoftheargumentroundedtothenearest *{@codelong}value. *@seejava.lang.Long#MAX_VALUE *@seejava.lang.Long#MIN_VALUE
*/
@IntrinsicCandidate publicstaticlong round(double a) { long longBits = Double.doubleToRawLongBits(a); long biasedExp = (longBits & DoubleConsts.EXP_BIT_MASK)
>> (DoubleConsts.SIGNIFICAND_WIDTH - 1); long shift = (DoubleConsts.SIGNIFICAND_WIDTH - 2
+ DoubleConsts.EXP_BIAS) - biasedExp; if ((shift & -64) == 0) { // shift >= 0 && shift < 64 // a is a finite number such that pow(2,-64) <= ulp(a) < 1 long r = ((longBits & DoubleConsts.SIGNIF_BIT_MASK)
| (DoubleConsts.SIGNIF_BIT_MASK + 1)); if (longBits < 0) {
r = -r;
} // In the comments below each Java expression evaluates to the value // the corresponding mathematical expression: // (r) evaluates to a / ulp(a) // (r >> shift) evaluates to floor(a * 2) // ((r >> shift) + 1) evaluates to floor((a + 1/2) * 2) // (((r >> shift) + 1) >> 1) evaluates to floor(a + 1/2) return ((r >> shift) + 1) >> 1;
} else { // a is either // - a finite number with abs(a) < exp(2,DoubleConsts.SIGNIFICAND_WIDTH-64) < 1/2 // - a finite number with ulp(a) >= 1 and hence a is a mathematical integer // - an infinity or NaN return (long) a;
}
}
privatestaticfinalclass RandomNumberGeneratorHolder { staticfinal Random randomNumberGenerator = new Random();
}
/** *Returnsthesumofitsarguments, *throwinganexceptioniftheresultoverflowsan{@codeint}. * *@paramxthefirstvalue *@paramythesecondvalue *@returntheresult *@throwsArithmeticExceptioniftheresultoverflowsanint *@since1.8
*/
@IntrinsicCandidate publicstaticint addExact(int x, int y) { int r = x + y; // HD 2-12 Overflow iff both arguments have the opposite sign of the result if (((x ^ r) & (y ^ r)) < 0) { thrownew ArithmeticException("integer overflow");
} return r;
}
/** *Returnsthesumofitsarguments, *throwinganexceptioniftheresultoverflowsa{@codelong}. * *@paramxthefirstvalue *@paramythesecondvalue *@returntheresult *@throwsArithmeticExceptioniftheresultoverflowsalong *@since1.8
*/
@IntrinsicCandidate publicstaticlong addExact(long x, long y) { long r = x + y; // HD 2-12 Overflow iff both arguments have the opposite sign of the result if (((x ^ r) & (y ^ r)) < 0) { thrownew ArithmeticException("long overflow");
} return r;
}
/** *Returnsthedifferenceofthearguments, *throwinganexceptioniftheresultoverflowsan{@codeint}. * *@paramxthefirstvalue *@paramythesecondvaluetosubtractfromthefirst *@returntheresult *@throwsArithmeticExceptioniftheresultoverflowsanint *@since1.8
*/
@IntrinsicCandidate publicstaticint subtractExact(int x, int y) { int r = x - y; // HD 2-12 Overflow iff the arguments have different signs and // the sign of the result is different from the sign of x if (((x ^ y) & (x ^ r)) < 0) { thrownew ArithmeticException("integer overflow");
} return r;
}
/** *Returnsthedifferenceofthearguments, *throwinganexceptioniftheresultoverflowsa{@codelong}. * *@paramxthefirstvalue *@paramythesecondvaluetosubtractfromthefirst *@returntheresult *@throwsArithmeticExceptioniftheresultoverflowsalong *@since1.8
*/
@IntrinsicCandidate publicstaticlong subtractExact(long x, long y) { long r = x - y; // HD 2-12 Overflow iff the arguments have different signs and // the sign of the result is different from the sign of x if (((x ^ y) & (x ^ r)) < 0) { thrownew ArithmeticException("long overflow");
} return r;
}
/** *Returnstheproductofthearguments, *throwinganexceptioniftheresultoverflowsan{@codeint}. * *@paramxthefirstvalue *@paramythesecondvalue *@returntheresult *@throwsArithmeticExceptioniftheresultoverflowsanint *@since1.8
*/
@IntrinsicCandidate publicstaticint multiplyExact(int x, int y) { long r = (long)x * (long)y; if ((int)r != r) { thrownew ArithmeticException("integer overflow");
} return (int)r;
}
/** *Returnstheproductofthearguments, *throwinganexceptioniftheresultoverflowsa{@codelong}. * *@paramxthefirstvalue *@paramythesecondvalue *@returntheresult *@throwsArithmeticExceptioniftheresultoverflowsalong *@since1.8
*/
@IntrinsicCandidate publicstaticlong multiplyExact(long x, long y) { long r = x * y; long ax = Math.abs(x); long ay = Math.abs(y); if (((ax | ay) >>> 31 != 0)) { // Some bits greater than 2^31 that might cause overflow // Check the result using the divide operator // and check for the special case of Long.MIN_VALUE * -1 if (((y != 0) && (r / y != x)) ||
(x == Long.MIN_VALUE && y == -1)) { thrownew ArithmeticException("long overflow");
}
} return r;
}
/** *Returnsthequotientofthearguments,throwinganexceptionifthe *resultoverflowsan{@codeint}.Suchoverflowoccursinthismethodif *{@codex}is{@linkInteger#MIN_VALUE}and{@codey}is{@code-1}. *Incontrast,if{@codeInteger.MIN_VALUE/-1}wereevaluateddirectly, *theresultwouldbe{@codeInteger.MIN_VALUE}andnoexceptionwouldbe *thrown. *<p> *If{@codey}iszero,an{@codeArithmeticException}isthrown *(JLS{@jls15.17.2}). *<p> *Thebuilt-inremainderoperator"{@code%}"isasuitablecounterpart *bothforthismethodandforthebuilt-indivisionoperator"{@code/}". * *@paramxthedividend *@paramythedivisor *@returnthequotient{@codex/y} *@throwsArithmeticExceptionif{@codey}iszeroorthequotient *overflowsanint *@jls15.17.2DivisionOperator/ *@since18
*/ publicstaticint divideExact(int x, int y) { int q = x / y; if ((x & y & q) >= 0) { return q;
} thrownew ArithmeticException("integer overflow");
}
/** *Returnsthequotientofthearguments,throwinganexceptionifthe *resultoverflowsa{@codelong}.Suchoverflowoccursinthismethodif *{@codex}is{@linkLong#MIN_VALUE}and{@codey}is{@code-1}. *Incontrast,if{@codeLong.MIN_VALUE/-1}wereevaluateddirectly, *theresultwouldbe{@codeLong.MIN_VALUE}andnoexceptionwouldbe *thrown. *<p> *If{@codey}iszero,an{@codeArithmeticException}isthrown *(JLS{@jls15.17.2}). *<p> *Thebuilt-inremainderoperator"{@code%}"isasuitablecounterpart *bothforthismethodandforthebuilt-indivisionoperator"{@code/}". * *@paramxthedividend *@paramythedivisor *@returnthequotient{@codex/y} *@throwsArithmeticExceptionif{@codey}iszeroorthequotient *overflowsalong *@jls15.17.2DivisionOperator/ *@since18
*/ publicstaticlong divideExact(long x, long y) { long q = x / y; if ((x & y & q) >= 0) { return q;
} thrownew ArithmeticException("long overflow");
}
/** *Returnsthelargest(closesttopositiveinfinity) *{@codeint}valuethatislessthanorequaltothealgebraicquotient. *Thismethodisidenticalto{@link#floorDiv(int,int)}exceptthatit *throwsan{@codeArithmeticException}whenthedividendis *{@linkplainInteger#MIN_VALUEInteger.MIN_VALUE}andthedivisoris *{@code-1}insteadofignoringtheintegeroverflowandreturning *{@codeInteger.MIN_VALUE}. *<p> *Thefloormodulusmethod{@link#floorMod(int,int)}isasuitable *counterpartbothforthismethodandforthe{@link#floorDiv(int,int)} *method. *<p> *Forexamples,see{@link#floorDiv(int,int)}. * *@paramxthedividend *@paramythedivisor *@returnthelargest(closesttopositiveinfinity) *{@codeint}valuethatislessthanorequaltothealgebraicquotient. *@throwsArithmeticExceptionifthedivisor{@codey}iszero,orthe *dividend{@codex}is{@codeInteger.MIN_VALUE}andthedivisor{@codey} *is{@code-1}. *@see#floorDiv(int,int) *@since18
*/ publicstaticint floorDivExact(int x, int y) { finalint q = x / y; if ((x & y & q) >= 0) { // if the signs are different and modulo not zero, round down if ((x ^ y) < 0 && (q * y != x)) { return q - 1;
} return q;
} thrownew ArithmeticException("integer overflow");
}
/** *Returnsthelargest(closesttopositiveinfinity) *{@codelong}valuethatislessthanorequaltothealgebraicquotient. *Thismethodisidenticalto{@link#floorDiv(long,long)}exceptthatit *throwsan{@codeArithmeticException}whenthedividendis *{@linkplainLong#MIN_VALUELong.MIN_VALUE}andthedivisoris *{@code-1}insteadofignoringtheintegeroverflowandreturning *{@codeLong.MIN_VALUE}. *<p> *Thefloormodulusmethod{@link#floorMod(long,long)}isasuitable *counterpartbothforthismethodandforthe{@link#floorDiv(long,long)} *method. *<p> *Forexamples,see{@link#floorDiv(int,int)}. * *@paramxthedividend *@paramythedivisor *@returnthelargest(closesttopositiveinfinity) *{@codelong}valuethatislessthanorequaltothealgebraicquotient. *@throwsArithmeticExceptionifthedivisor{@codey}iszero,orthe *dividend{@codex}is{@codeLong.MIN_VALUE}andthedivisor{@codey} *is{@code-1}. *@see#floorDiv(long,long) *@since18
*/ publicstaticlong floorDivExact(long x, long y) { finallong q = x / y; if ((x & y & q) >= 0) { // if the signs are different and modulo not zero, round down if ((x ^ y) < 0 && (q * y != x)) { return q - 1;
} return q;
} thrownew ArithmeticException("long overflow");
}
/** *Returnsthesmallest(closesttonegativeinfinity) *{@codeint}valuethatisgreaterthanorequaltothealgebraicquotient. *Thismethodisidenticalto{@link#ceilDiv(int,int)}exceptthatit *throwsan{@codeArithmeticException}whenthedividendis *{@linkplainInteger#MIN_VALUEInteger.MIN_VALUE}andthedivisoris *{@code-1}insteadofignoringtheintegeroverflowandreturning *{@codeInteger.MIN_VALUE}. *<p> *Theceilmodulusmethod{@link#ceilMod(int,int)}isasuitable *counterpartbothforthismethodandforthe{@link#ceilDiv(int,int)} *method. *<p> *Forexamples,see{@link#ceilDiv(int,int)}. * *@paramxthedividend *@paramythedivisor *@returnthesmallest(closesttonegativeinfinity) *{@codeint}valuethatisgreaterthanorequaltothealgebraicquotient. *@throwsArithmeticExceptionifthedivisor{@codey}iszero,orthe *dividend{@codex}is{@codeInteger.MIN_VALUE}andthedivisor{@codey} *is{@code-1}. *@see#ceilDiv(int,int) *@since18
*/ publicstaticint ceilDivExact(int x, int y) { finalint q = x / y; if ((x & y & q) >= 0) { // if the signs are the same and modulo not zero, round up if ((x ^ y) >= 0 && (q * y != x)) { return q + 1;
} return q;
} thrownew ArithmeticException("integer overflow");
}
/** *Returnsthesmallest(closesttonegativeinfinity) *{@codelong}valuethatisgreaterthanorequaltothealgebraicquotient. *Thismethodisidenticalto{@link#ceilDiv(long,long)}exceptthatit *throwsan{@codeArithmeticException}whenthedividendis *{@linkplainLong#MIN_VALUELong.MIN_VALUE}andthedivisoris *{@code-1}insteadofignoringtheintegeroverflowandreturning *{@codeLong.MIN_VALUE}. *<p> *Theceilmodulusmethod{@link#ceilMod(long,long)}isasuitable *counterpartbothforthismethodandforthe{@link#ceilDiv(long,long)} *method. *<p> *Forexamples,see{@link#ceilDiv(int,int)}. * *@paramxthedividend *@paramythedivisor *@returnthesmallest(closesttonegativeinfinity) *{@codelong}valuethatisgreaterthanorequaltothealgebraicquotient. *@throwsArithmeticExceptionifthedivisor{@codey}iszero,orthe *dividend{@codex}is{@codeLong.MIN_VALUE}andthedivisor{@codey} *is{@code-1}. *@see#ceilDiv(long,long) *@since18
*/ publicstaticlong ceilDivExact(long x, long y) { finallong q = x / y; if ((x & y & q) >= 0) { // if the signs are the same and modulo not zero, round up if ((x ^ y) >= 0 && (q * y != x)) { return q + 1;
} return q;
} thrownew ArithmeticException("long overflow");
}
/** *Returnstheargumentincrementedbyone,throwinganexceptionifthe *resultoverflowsan{@codeint}. *Theoverflowonlyoccursfor{@linkplainInteger#MAX_VALUEthemaximumvalue}. * *@paramathevaluetoincrement *@returntheresult *@throwsArithmeticExceptioniftheresultoverflowsanint *@since1.8
*/
@IntrinsicCandidate publicstaticint incrementExact(int a) { if (a == Integer.MAX_VALUE) { thrownew ArithmeticException("integer overflow");
}
return a + 1;
}
/** *Returnstheargumentincrementedbyone,throwinganexceptionifthe *resultoverflowsa{@codelong}. *Theoverflowonlyoccursfor{@linkplainLong#MAX_VALUEthemaximumvalue}. * *@paramathevaluetoincrement *@returntheresult *@throwsArithmeticExceptioniftheresultoverflowsalong *@since1.8
*/
@IntrinsicCandidate publicstaticlong incrementExact(long a) { if (a == Long.MAX_VALUE) { thrownew ArithmeticException("long overflow");
}
return a + 1L;
}
/** *Returnstheargumentdecrementedbyone,throwinganexceptionifthe *resultoverflowsan{@codeint}. *Theoverflowonlyoccursfor{@linkplainInteger#MIN_VALUEtheminimumvalue}. * *@paramathevaluetodecrement *@returntheresult *@throwsArithmeticExceptioniftheresultoverflowsanint *@since1.8
*/
@IntrinsicCandidate publicstaticint decrementExact(int a) { if (a == Integer.MIN_VALUE) { thrownew ArithmeticException("integer overflow");
}
return a - 1;
}
/** *Returnstheargumentdecrementedbyone,throwinganexceptionifthe *resultoverflowsa{@codelong}. *Theoverflowonlyoccursfor{@linkplainLong#MIN_VALUEtheminimumvalue}. * *@paramathevaluetodecrement *@returntheresult *@throwsArithmeticExceptioniftheresultoverflowsalong *@since1.8
*/
@IntrinsicCandidate publicstaticlong decrementExact(long a) { if (a == Long.MIN_VALUE) { thrownew ArithmeticException("long overflow");
}
return a - 1L;
}
/** *Returnsthenegationoftheargument,throwinganexceptionifthe *resultoverflowsan{@codeint}. *Theoverflowonlyoccursfor{@linkplainInteger#MIN_VALUEtheminimumvalue}. * *@paramathevaluetonegate *@returntheresult *@throwsArithmeticExceptioniftheresultoverflowsanint *@since1.8
*/
@IntrinsicCandidate publicstaticint negateExact(int a) { if (a == Integer.MIN_VALUE) { thrownew ArithmeticException("integer overflow");
}
return -a;
}
/** *Returnsthenegationoftheargument,throwinganexceptionifthe *resultoverflowsa{@codelong}. *Theoverflowonlyoccursfor{@linkplainLong#MIN_VALUEtheminimumvalue}. * *@paramathevaluetonegate *@returntheresult *@throwsArithmeticExceptioniftheresultoverflowsalong *@since1.8
*/
@IntrinsicCandidate publicstaticlong negateExact(long a) { if (a == Long.MIN_VALUE) { thrownew ArithmeticException("long overflow");
}
/** *Returnsasa{@codelong}themostsignificant64bitsofthe128-bit *productoftwo64-bitfactors. * *@paramxthefirstvalue *@paramythesecondvalue *@returntheresult *@see#unsignedMultiplyHigh *@since9
*/
@IntrinsicCandidate publicstaticlong multiplyHigh(long x, long y) { // Use technique from section 8-2 of Henry S. Warren, Jr., // Hacker's Delight (2nd ed.) (Addison Wesley, 2013), 173-174. long x1 = x >> 32; long x2 = x & 0xFFFFFFFFL; long y1 = y >> 32; long y2 = y & 0xFFFFFFFFL;
long z2 = x2 * y2; long t = x1 * y2 + (z2 >>> 32); long z1 = t & 0xFFFFFFFFL; long z0 = t >> 32;
z1 += x2 * y1;
return x1 * y1 + z0 + (z1 >> 32);
}
/** *Returnsasa{@codelong}themostsignificant64bitsoftheunsigned *128-bitproductoftwounsigned64-bitfactors. * *@paramxthefirstvalue *@paramythesecondvalue *@returntheresult *@see#multiplyHigh *@since18
*/
@IntrinsicCandidate publicstaticlong unsignedMultiplyHigh(long x, long y) { // Compute via multiplyHigh() to leverage the intrinsic long result = Math.multiplyHigh(x, y);
result += (y & (x >> 63)); // equivalent to `if (x < 0) result += y;`
result += (x & (y >> 63)); // equivalent to `if (y < 0) result += x;` return result;
}
/** *Returnsthelargest(closesttopositiveinfinity) *{@codeint}valuethatislessthanorequaltothealgebraicquotient. *Thereisonespecialcase:ifthedividendis *{@linkplainInteger#MIN_VALUEInteger.MIN_VALUE}andthedivisoris{@code-1}, *thenintegeroverflowoccursand *theresultisequalto{@codeInteger.MIN_VALUE}. *<p> *Normalintegerdivisionoperatesundertheroundtozeroroundingmode *(truncation).Thisoperationinsteadactsundertheroundtoward *negativeinfinity(floor)roundingmode. *Thefloorroundingmodegivesdifferentresultsfromtruncation *whentheexactquotientisnotanintegerandisnegative. *<ul> *<li>Ifthesignsoftheargumentsarethesame,theresultsof *{@codefloorDiv}andthe{@code/}operatorarethesame.<br> *Forexample,{@codefloorDiv(4,3)==1}and{@code(4/3)==1}.</li> *<li>Ifthesignsoftheargumentsaredifferent,{@codefloorDiv} *returnsthelargestintegerlessthanorequaltothequotient *whilethe{@code/}operatorreturnsthesmallestintegergreater *thanorequaltothequotient. *Theydifferifandonlyifthequotientisnotaninteger.<br> *Forexample,{@codefloorDiv(-4,3)==-2}, *whereas{@code(-4/3)==-1}. *</li> *</ul> * *@paramxthedividend *@paramythedivisor *@returnthelargest(closesttopositiveinfinity) *{@codeint}valuethatislessthanorequaltothealgebraicquotient. *@throwsArithmeticExceptionifthedivisor{@codey}iszero *@see#floorMod(int,int) *@see#floor(double) *@since1.8
*/ publicstaticint floorDiv(int x, int y) { finalint q = x / y; // if the signs are different and modulo not zero, round down if ((x ^ y) < 0 && (q * y != x)) { return q - 1;
} return q;
}
/** *Returnsthelargest(closesttopositiveinfinity) *{@codelong}valuethatislessthanorequaltothealgebraicquotient. *Thereisonespecialcase:ifthedividendis *{@linkplainLong#MIN_VALUELong.MIN_VALUE}andthedivisoris{@code-1}, *thenintegeroverflowoccursand *theresultisequalto{@codeLong.MIN_VALUE}. *<p> *Normalintegerdivisionoperatesundertheroundtozeroroundingmode *(truncation).Thisoperationinsteadactsundertheroundtoward *negativeinfinity(floor)roundingmode. *Thefloorroundingmodegivesdifferentresultsfromtruncation *whentheexactresultisnotanintegerandisnegative. *<p> *Forexamples,see{@link#floorDiv(int,int)}. * *@paramxthedividend *@paramythedivisor *@returnthelargest(closesttopositiveinfinity) *{@codelong}valuethatislessthanorequaltothealgebraicquotient. *@throwsArithmeticExceptionifthedivisor{@codey}iszero *@see#floorMod(long,long) *@see#floor(double) *@since1.8
*/ publicstaticlong floorDiv(long x, long y) { finallong q = x / y; // if the signs are different and modulo not zero, round down if ((x ^ y) < 0 && (q * y != x)) { return q - 1;
} return q;
}
/** *Returnsthefloormodulusofthe{@codeint}arguments. *<p> *Thefloormodulusis{@coder=x-(floorDiv(x,y)*y)}, *hasthesamesignasthedivisor{@codey}oriszero,and *isintherangeof{@code-abs(y)<r<+abs(y)}. * *<p> *Therelationshipbetween{@codefloorDiv}and{@codefloorMod}issuchthat: *<ul> *<li>{@codefloorDiv(x,y)*y+floorMod(x,y)==x}</li> *</ul> *<p> *Thedifferenceinvaluesbetween{@codefloorMod}andthe{@code%}operator *isduetothedifferencebetween{@codefloorDiv}andthe{@code/} *operator,asdetailedin{@linkplain#floorDiv(int,int)}. *<p> *Examples: *<ul> *<li>Regardlessofthesignsofthearguments,{@codefloorMod}(x,y) *iszeroexactlywhen{@codex%y}iszeroaswell.</li> *<li>Ifneither{@codefloorMod}(x,y)nor{@codex%y}iszero, *theydifferexactlywhenthesignsoftheargumentsdiffer.<br> *<ul> *<li>{@codefloorMod(+4,+3)==+1}; and{@code(+4%+3)==+1}</li> *<li>{@codefloorMod(-4,-3)==-1}; and{@code(-4%-3)==-1}</li> *<li>{@codefloorMod(+4,-3)==-2}; and{@code(+4%-3)==+1}</li> *<li>{@codefloorMod(-4,+3)==+2}; and{@code(-4%+3)==-1}</li> *</ul> *</li> *</ul> * *@paramxthedividend *@paramythedivisor *@returnthefloormodulus{@codex-(floorDiv(x,y)*y)} *@throwsArithmeticExceptionifthedivisor{@codey}iszero *@see#floorDiv(int,int) *@since1.8
*/ publicstaticint floorMod(int x, int y) { finalint r = x % y; // if the signs are different and modulo not zero, adjust result if ((x ^ y) < 0 && r != 0) { return r + y;
} return r;
}
/** *Returnsthefloormodulusofthe{@codelong}and{@codeint}arguments. *<p> *Thefloormodulusis{@coder=x-(floorDiv(x,y)*y)}, *hasthesamesignasthedivisor{@codey}oriszero,and *isintherangeof{@code-abs(y)<r<+abs(y)}. * *<p> *Therelationshipbetween{@codefloorDiv}and{@codefloorMod}issuchthat: *<ul> *<li>{@codefloorDiv(x,y)*y+floorMod(x,y)==x}</li> *</ul> *<p> *Forexamples,see{@link#floorMod(int,int)}. * *@paramxthedividend *@paramythedivisor *@returnthefloormodulus{@codex-(floorDiv(x,y)*y)} *@throwsArithmeticExceptionifthedivisor{@codey}iszero *@see#floorDiv(long,int) *@since9
*/ publicstaticint floorMod(long x, int y) { // Result cannot overflow the range of int. return (int)floorMod(x, (long)y);
}
/** *Returnsthefloormodulusofthe{@codelong}arguments. *<p> *Thefloormodulusis{@coder=x-(floorDiv(x,y)*y)}, *hasthesamesignasthedivisor{@codey}oriszero,and *isintherangeof{@code-abs(y)<r<+abs(y)}. * *<p> *Therelationshipbetween{@codefloorDiv}and{@codefloorMod}issuchthat: *<ul> *<li>{@codefloorDiv(x,y)*y+floorMod(x,y)==x}</li> *</ul> *<p> *Forexamples,see{@link#floorMod(int,int)}. * *@paramxthedividend *@paramythedivisor *@returnthefloormodulus{@codex-(floorDiv(x,y)*y)} *@throwsArithmeticExceptionifthedivisor{@codey}iszero *@see#floorDiv(long,long) *@since1.8
*/ publicstaticlong floorMod(long x, long y) { finallong r = x % y; // if the signs are different and modulo not zero, adjust result if ((x ^ y) < 0 && r != 0) { return r + y;
} return r;
}
/** *Returnsthesmallest(closesttonegativeinfinity) *{@codeint}valuethatisgreaterthanorequaltothealgebraicquotient. *Thereisonespecialcase:ifthedividendis *{@linkplainInteger#MIN_VALUEInteger.MIN_VALUE}andthedivisoris{@code-1}, *thenintegeroverflowoccursand *theresultisequalto{@codeInteger.MIN_VALUE}. *<p> *Normalintegerdivisionoperatesundertheroundtozeroroundingmode *(truncation).Thisoperationinsteadactsundertheroundtoward *positiveinfinity(ceiling)roundingmode. *Theceilingroundingmodegivesdifferentresultsfromtruncation *whentheexactquotientisnotanintegerandispositive. *<ul> *<li>Ifthesignsoftheargumentsaredifferent,theresultsof *{@codeceilDiv}andthe{@code/}operatorarethesame.<br> *Forexample,{@codeceilDiv(-4,3)==-1}and{@code(-4/3)==-1}.</li> *<li>Ifthesignsoftheargumentsarethesame,{@codeceilDiv} *returnsthesmallestintegergreaterthanorequaltothequotient *whilethe{@code/}operatorreturnsthelargestintegerless *thanorequaltothequotient. *Theydifferifandonlyifthequotientisnotaninteger.<br> *Forexample,{@codeceilDiv(4,3)==2}, *whereas{@code(4/3)==1}. *</li> *</ul> * *@paramxthedividend *@paramythedivisor *@returnthesmallest(closesttonegativeinfinity) *{@codeint}valuethatisgreaterthanorequaltothealgebraicquotient. *@throwsArithmeticExceptionifthedivisor{@codey}iszero *@see#ceilMod(int,int) *@see#ceil(double) *@since18
*/ publicstaticint ceilDiv(int x, int y) { finalint q = x / y; // if the signs are the same and modulo not zero, round up if ((x ^ y) >= 0 && (q * y != x)) { return q + 1;
} return q;
}
/** *Returnsthesmallest(closesttonegativeinfinity) *{@codelong}valuethatisgreaterthanorequaltothealgebraicquotient. *Thereisonespecialcase:ifthedividendis *{@linkplainLong#MIN_VALUELong.MIN_VALUE}andthedivisoris{@code-1}, *thenintegeroverflowoccursand *theresultisequalto{@codeLong.MIN_VALUE}. *<p> *Normalintegerdivisionoperatesundertheroundtozeroroundingmode *(truncation).Thisoperationinsteadactsundertheroundtoward *positiveinfinity(ceiling)roundingmode. *Theceilingroundingmodegivesdifferentresultsfromtruncation *whentheexactresultisnotanintegerandispositive. *<p> *Forexamples,see{@link#ceilDiv(int,int)}. * *@paramxthedividend *@paramythedivisor *@returnthesmallest(closesttonegativeinfinity) *{@codelong}valuethatisgreaterthanorequaltothealgebraicquotient. *@throwsArithmeticExceptionifthedivisor{@codey}iszero *@see#ceilMod(int,int) *@see#ceil(double) *@since18
*/ publicstaticlong ceilDiv(long x, long y) { finallong q = x / y; // if the signs are the same and modulo not zero, round up if ((x ^ y) >= 0 && (q * y != x)) { return q + 1;
} return q;
}
/** *Returnstheceilingmodulusofthe{@codeint}arguments. *<p> *Theceilingmodulusis{@coder=x-(ceilDiv(x,y)*y)}, *hastheoppositesignasthedivisor{@codey}oriszero,and *isintherangeof{@code-abs(y)<r<+abs(y)}. * *<p> *Therelationshipbetween{@codeceilDiv}and{@codeceilMod}issuchthat: *<ul> *<li>{@codeceilDiv(x,y)*y+ceilMod(x,y)==x}</li> *</ul> *<p> *Thedifferenceinvaluesbetween{@codeceilMod}andthe{@code%}operator *isduetothedifferencebetween{@codeceilDiv}andthe{@code/} *operator,asdetailedin{@linkplain#ceilDiv(int,int)}. *<p> *Examples: *<ul> *<li>Regardlessofthesignsofthearguments,{@codeceilMod}(x,y) *iszeroexactlywhen{@codex%y}iszeroaswell.</li> *<li>Ifneither{@codeceilMod}(x,y)nor{@codex%y}iszero, *theydifferexactlywhenthesignsoftheargumentsarethesame.<br> *<ul> *<li>{@codeceilMod(+4,+3)==-2}; and{@code(+4%+3)==+1}</li> *<li>{@codeceilMod(-4,-3)==+2}; and{@code(-4%-3)==-1}</li> *<li>{@codeceilMod(+4,-3)==+1}; and{@code(+4%-3)==+1}</li> *<li>{@codeceilMod(-4,+3)==-1}; and{@code(-4%+3)==-1}</li> *</ul> *</li> *</ul> * *@paramxthedividend *@paramythedivisor *@returntheceilingmodulus{@codex-(ceilDiv(x,y)*y)} *@throwsArithmeticExceptionifthedivisor{@codey}iszero *@see#ceilDiv(int,int) *@since18
*/ publicstaticint ceilMod(int x, int y) { finalint r = x % y; // if the signs are the same and modulo not zero, adjust result if ((x ^ y) >= 0 && r != 0) { return r - y;
} return r;
}
/** *Returnstheceilingmodulusofthe{@codelong}and{@codeint}arguments. *<p> *Theceilingmodulusis{@coder=x-(ceilDiv(x,y)*y)}, *hastheoppositesignasthedivisor{@codey}oriszero,and *isintherangeof{@code-abs(y)<r<+abs(y)}. * *<p> *Therelationshipbetween{@codeceilDiv}and{@codeceilMod}issuchthat: *<ul> *<li>{@codeceilDiv(x,y)*y+ceilMod(x,y)==x}</li> *</ul> *<p> *Forexamples,see{@link#ceilMod(int,int)}. * *@paramxthedividend *@paramythedivisor *@returntheceilingmodulus{@codex-(ceilDiv(x,y)*y)} *@throwsArithmeticExceptionifthedivisor{@codey}iszero *@see#ceilDiv(long,int) *@since18
*/ publicstaticint ceilMod(long x, int y) { // Result cannot overflow the range of int. return (int)ceilMod(x, (long)y);
}
/** *Returnstheceilingmodulusofthe{@codelong}arguments. *<p> *Theceilingmodulusis{@coder=x-(ceilDiv(x,y)*y)}, *hastheoppositesignasthedivisor{@codey}oriszero,and *isintherangeof{@code-abs(y)<r<+abs(y)}. * *<p> *Therelationshipbetween{@codeceilDiv}and{@codeceilMod}issuchthat: *<ul> *<li>{@codeceilDiv(x,y)*y+ceilMod(x,y)==x}</li> *</ul> *<p> *Forexamples,see{@link#ceilMod(int,int)}. * *@paramxthedividend *@paramythedivisor *@returntheceilingmodulus{@codex-(ceilDiv(x,y)*y)} *@throwsArithmeticExceptionifthedivisor{@codey}iszero *@see#ceilDiv(long,long) *@since18
*/ publicstaticlong ceilMod(long x, long y) { finallong r = x % y; // if the signs are the same and modulo not zero, adjust result if ((x ^ y) >= 0 && r != 0) { return r - y;
} return r;
}
/** *Returnstheabsolutevalueofan{@codeint}value. *Iftheargumentisnotnegative,theargumentisreturned. *Iftheargumentisnegative,thenegationoftheargumentisreturned. * *<p>Notethatiftheargumentisequaltothevalueof{@link *Integer#MIN_VALUE},themostnegativerepresentable{@codeint} *value,theresultisthatsamevalue,whichisnegative.In *contrast,the{@linkMath#absExact(int)}methodthrowsan *{@codeArithmeticException}forthisvalue. * *@paramatheargumentwhoseabsolutevalueistobedetermined *@returntheabsolutevalueoftheargument. *@seeMath#absExact(int)
*/
@IntrinsicCandidate publicstaticint abs(int a) { return (a < 0) ? -a : a;
}
/** *Returnsthemathematicalabsolutevalueofan{@codeint}value *ifitisexactlyrepresentableasan{@codeint},throwing *{@codeArithmeticException}iftheresultoverflowsthe *positive{@codeint}range. * *<p>Sincetherangeoftwo'scomplementintegersisasymmetric *withoneadditionalnegativevalue(JLS{@jls4.2.1}),the *mathematicalabsolutevalueof{@linkInteger#MIN_VALUE} *overflowsthepositive{@codeint}range,soanexceptionis *thrownforthatargument. * *@paramatheargumentwhoseabsolutevalueistobedetermined *@returntheabsolutevalueoftheargument,unlessoverflowoccurs *@throwsArithmeticExceptioniftheargumentis{@linkInteger#MIN_VALUE} *@seeMath#abs(int) *@since15
*/ publicstaticint absExact(int a) { if (a == Integer.MIN_VALUE) thrownew ArithmeticException( "Overflow to represent absolute value of Integer.MIN_VALUE"); else return abs(a);
}
/** *Returnstheabsolutevalueofa{@codelong}value. *Iftheargumentisnotnegative,theargumentisreturned. *Iftheargumentisnegative,thenegationoftheargumentisreturned. * *<p>Notethatiftheargumentisequaltothevalueof{@link *Long#MIN_VALUE},themostnegativerepresentable{@codelong} *value,theresultisthatsamevalue,whichisnegative.In *contrast,the{@linkMath#absExact(long)}methodthrowsan *{@codeArithmeticException}forthisvalue. * *@paramatheargumentwhoseabsolutevalueistobedetermined *@returntheabsolutevalueoftheargument. *@seeMath#absExact(long)
*/
@IntrinsicCandidate publicstaticlong abs(long a) { return (a < 0) ? -a : a;
}
/** *Returnsthemathematicalabsolutevalueofan{@codelong}value *ifitisexactlyrepresentableasan{@codelong},throwing *{@codeArithmeticException}iftheresultoverflowsthe *positive{@codelong}range. * *<p>Sincetherangeoftwo'scomplementintegersisasymmetric *withoneadditionalnegativevalue(JLS{@jls4.2.1}),the *mathematicalabsolutevalueof{@linkLong#MIN_VALUE}overflows *thepositive{@codelong}range,soanexceptionisthrownfor *thatargument. * *@paramatheargumentwhoseabsolutevalueistobedetermined *@returntheabsolutevalueoftheargument,unlessoverflowoccurs *@throwsArithmeticExceptioniftheargumentis{@linkLong#MIN_VALUE} *@seeMath#abs(long) *@since15
*/ publicstaticlong absExact(long a) { if (a == Long.MIN_VALUE) thrownew ArithmeticException( "Overflow to represent absolute value of Long.MIN_VALUE"); else return abs(a);
}
/** *Returnstheabsolutevalueofa{@codefloat}value. *Iftheargumentisnotnegative,theargumentisreturned. *Iftheargumentisnegative,thenegationoftheargumentisreturned. *Specialcases: *<ul><li>Iftheargumentispositivezeroornegativezero,the *resultispositivezero. *<li>Iftheargumentisinfinite,theresultispositiveinfinity. *<li>IftheargumentisNaN,theresultisNaN.</ul> * *@apiNoteAsimpliedbytheabove,onevalidimplementationof *thismethodisgivenbytheexpressionbelowwhichcomputesa *{@codefloat}withthesameexponentandsignificandasthe *argumentbutwithaguaranteedzerosignbitindicatinga *positivevalue:<br> *{@codeFloat.intBitsToFloat(0x7fffffff&Float.floatToRawIntBits(a))} * *@paramatheargumentwhoseabsolutevalueistobedetermined *@returntheabsolutevalueoftheargument.
*/
@IntrinsicCandidate publicstaticfloat abs(float a) { // Convert to bit field form, zero the sign bit, and convert back returnFloat.intBitsToFloat(Float.floatToRawIntBits(a) & FloatConsts.MAG_BIT_MASK);
}
/** *Returnstheabsolutevalueofa{@codedouble}value. *Iftheargumentisnotnegative,theargumentisreturned. *Iftheargumentisnegative,thenegationoftheargumentisreturned. *Specialcases: *<ul><li>Iftheargumentispositivezeroornegativezero,theresult *ispositivezero. *<li>Iftheargumentisinfinite,theresultispositiveinfinity. *<li>IftheargumentisNaN,theresultisNaN.</ul> * *@apiNoteAsimpliedbytheabove,onevalidimplementationof *thismethodisgivenbytheexpressionbelowwhichcomputesa *{@codedouble}withthesameexponentandsignificandasthe *argumentbutwithaguaranteedzerosignbitindicatinga *positivevalue:<br> *{@codeDouble.longBitsToDouble((Double.doubleToRawLongBits(a)<<1)>>>1)} * *@paramatheargumentwhoseabsolutevalueistobedetermined *@returntheabsolutevalueoftheargument.
*/
@IntrinsicCandidate publicstaticdouble abs(double a) { // Convert to bit field form, zero the sign bit, and convert back returnDouble.longBitsToDouble(Double.doubleToRawLongBits(a) & DoubleConsts.MAG_BIT_MASK);
}
/** *Returnsthegreateroftwo{@codeint}values.Thatis,the *resultistheargumentclosertothevalueof *{@linkInteger#MAX_VALUE}.Iftheargumentshavethesamevalue, *theresultisthatsamevalue. * *@paramaanargument. *@parambanotherargument. *@returnthelargerof{@codea}and{@codeb}.
*/
@IntrinsicCandidate publicstaticint max(int a, int b) { return (a >= b) ? a : b;
}
/** *Returnsthegreateroftwo{@codelong}values.Thatis,the *resultistheargumentclosertothevalueof *{@linkLong#MAX_VALUE}.Iftheargumentshavethesamevalue, *theresultisthatsamevalue. * *@paramaanargument. *@parambanotherargument. *@returnthelargerof{@codea}and{@codeb}.
*/ publicstaticlong max(long a, long b) { return (a >= b) ? a : b;
}
// Use raw bit-wise conversions on guaranteed non-NaN arguments. privatestaticfinallong negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f); privatestaticfinallong negativeZeroDoubleBits = Double.doubleToRawLongBits(-0.0d);
/** *Returnsthegreateroftwo{@codefloat}values.Thatis, *theresultistheargumentclosertopositiveinfinity.Ifthe *argumentshavethesamevalue,theresultisthatsame *value.IfeithervalueisNaN,thentheresultisNaN.Unlike *thenumericalcomparisonoperators,thismethodconsiders *negativezerotobestrictlysmallerthanpositivezero.Ifone *argumentispositivezeroandtheothernegativezero,the *resultispositivezero. * *@apiNote *Thismethodcorrespondstothemaximumoperationdefinedin *IEEE754. * *@paramaanargument. *@parambanotherargument. *@returnthelargerof{@codea}and{@codeb}.
*/
@IntrinsicCandidate publicstaticfloat max(float a, float b) { if (a != a) return a; // a is NaN if ((a == 0.0f) &&
(b == 0.0f) &&
(Float.floatToRawIntBits(a) == negativeZeroFloatBits)) { // Raw conversion ok since NaN can't map to -0.0. return b;
} return (a >= b) ? a : b;
}
/** *Returnsthegreateroftwo{@codedouble}values.That *is,theresultistheargumentclosertopositiveinfinity.If *theargumentshavethesamevalue,theresultisthatsame *value.IfeithervalueisNaN,thentheresultisNaN.Unlike *thenumericalcomparisonoperators,thismethodconsiders *negativezerotobestrictlysmallerthanpositivezero.Ifone *argumentispositivezeroandtheothernegativezero,the *resultispositivezero. * *@apiNote *Thismethodcorrespondstothemaximumoperationdefinedin *IEEE754. * *@paramaanargument. *@parambanotherargument. *@returnthelargerof{@codea}and{@codeb}.
*/
@IntrinsicCandidate publicstaticdouble max(double a, double b) { if (a != a) return a; // a is NaN if ((a == 0.0d) &&
(b == 0.0d) &&
(Double.doubleToRawLongBits(a) == negativeZeroDoubleBits)) { // Raw conversion ok since NaN can't map to -0.0. return b;
} return (a >= b) ? a : b;
}
/** *Returnsthesmalleroftwo{@codeint}values.Thatis, *theresulttheargumentclosertothevalueof *{@linkInteger#MIN_VALUE}.Iftheargumentshavethesame *value,theresultisthatsamevalue. * *@paramaanargument. *@parambanotherargument. *@returnthesmallerof{@codea}and{@codeb}.
*/
@IntrinsicCandidate publicstaticint min(int a, int b) { return (a <= b) ? a : b;
}
/** *Returnsthesmalleroftwo{@codelong}values.Thatis, *theresultistheargumentclosertothevalueof *{@linkLong#MIN_VALUE}.Iftheargumentshavethesame *value,theresultisthatsamevalue. * *@paramaanargument. *@parambanotherargument. *@returnthesmallerof{@codea}and{@codeb}.
*/ publicstaticlong min(long a, long b) { return (a <= b) ? a : b;
}
/** *Returnsthesmalleroftwo{@codefloat}values.Thatis, *theresultisthevalueclosertonegativeinfinity.Ifthe *argumentshavethesamevalue,theresultisthatsame *value.IfeithervalueisNaN,thentheresultisNaN.Unlike *thenumericalcomparisonoperators,thismethodconsiders *negativezerotobestrictlysmallerthanpositivezero.If *oneargumentispositivezeroandtheotherisnegativezero, *theresultisnegativezero. * *@apiNote *Thismethodcorrespondstotheminimumoperationdefinedin *IEEE754. * *@paramaanargument. *@parambanotherargument. *@returnthesmallerof{@codea}and{@codeb}.
*/
@IntrinsicCandidate publicstaticfloat min(float a, float b) { if (a != a) return a; // a is NaN if ((a == 0.0f) &&
(b == 0.0f) &&
(Float.floatToRawIntBits(b) == negativeZeroFloatBits)) { // Raw conversion ok since NaN can't map to -0.0. return b;
} return (a <= b) ? a : b;
}
/** *Returnsthesmalleroftwo{@codedouble}values.That *is,theresultisthevalueclosertonegativeinfinity.Ifthe *argumentshavethesamevalue,theresultisthatsame *value.IfeithervalueisNaN,thentheresultisNaN.Unlike *thenumericalcomparisonoperators,thismethodconsiders *negativezerotobestrictlysmallerthanpositivezero.Ifone *argumentispositivezeroandtheotherisnegativezero,the *resultisnegativezero. * *@apiNote *Thismethodcorrespondstotheminimumoperationdefinedin *IEEE754. * *@paramaanargument. *@parambanotherargument. *@returnthesmallerof{@codea}and{@codeb}.
*/
@IntrinsicCandidate publicstaticdouble min(double a, double b) { if (a != a) return a; // a is NaN if ((a == 0.0d) &&
(b == 0.0d) &&
(Double.doubleToRawLongBits(b) == negativeZeroDoubleBits)) { // Raw conversion ok since NaN can't map to -0.0. return b;
} return (a <= b) ? a : b;
}
// First, screen for and handle non-finite input values whose // arithmetic is not supported by BigDecimal. if (Double.isNaN(a) || Double.isNaN(b) || Double.isNaN(c)) { returnDouble.NaN;
} else { // All inputs non-NaN boolean infiniteA = Double.isInfinite(a); boolean infiniteB = Double.isInfinite(b); boolean infiniteC = Double.isInfinite(c); double result;
if (infiniteA || infiniteB || infiniteC) { if (infiniteA && b == 0.0 ||
infiniteB && a == 0.0 ) { returnDouble.NaN;
} double product = a * b; if (Double.isInfinite(product) && !infiniteA && !infiniteB) { // Intermediate overflow; might cause a // spurious NaN if added to infinite c. assertDouble.isInfinite(c); return c;
} else {
result = product + c; assert !Double.isFinite(result); return result;
}
} else { // All inputs finite
BigDecimal product = (new BigDecimal(a)).multiply(new BigDecimal(b)); if (c == 0.0) { // Positive or negative zero // If the product is an exact zero, use a // floating-point expression to compute the sign // of the zero final result. The product is an // exact zero if and only if at least one of a and // b is zero. if (a == 0.0 || b == 0.0) { return a * b + c;
} else { // The sign of a zero addend doesn't matter if // the product is nonzero. The sign of a zero // addend is not factored in the result if the // exact product is nonzero but underflows to // zero; see IEEE-754 2008 section 6.3 "The // sign bit". return product.doubleValue();
}
} else { return product.add(new BigDecimal(c)).doubleValue();
}
}
}
}
/** *Returnsthefusedmultiplyaddofthethreearguments;thatis, *returnstheexactproductofthefirsttwoargumentssummed *withthethirdargumentandthenroundedoncetothenearest *{@codefloat}. * *Theroundingisdoneusingthe{@linkplain *java.math.RoundingMode#HALF_EVENroundtonearesteven *roundingmode}. * *Incontrast,if{@codea*b+c}isevaluatedasaregular *floating-pointexpression,tworoundingerrorsareinvolved, *thefirstforthemultiplyoperation,thesecondforthe *additionoperation. * *<p>Specialcases: *<ul> *<li>IfanyargumentisNaN,theresultisNaN. * *<li>Ifoneofthefirsttwoargumentsisinfiniteandthe *otheriszero,theresultisNaN. * *<li>Iftheexactproductofthefirsttwoargumentsisinfinite *(inotherwords,atleastoneoftheargumentsisinfiniteand *theotherisneitherzeronorNaN)andthethirdargumentisan *infinityoftheoppositesign,theresultisNaN. * *</ul> * *<p>Notethat{@codefma(a,1.0f,c)}returnsthesame *resultas({@codea+c}).However, *{@codefma(a,b,+0.0f)}does<em>not</em>alwaysreturnthe *sameresultas({@codea*b})since *{@codefma(-0.0f,+0.0f,+0.0f)}is{@code+0.0f}while *({@code-0.0f*+0.0f})is{@code-0.0f};{@codefma(a,b,-0.0f)}is *equivalentto({@codea*b})however. * *@apiNoteThismethodcorrespondstothefusedMultiplyAdd *operationdefinedinIEEE754. * *@paramaavalue *@parambavalue *@paramcavalue * *@return(<i>a</i> × <i>b</i> + <i>c</i>) *computed,asifwithunlimitedrangeandprecision,androunded *oncetothenearest{@codefloat}value * *@since9
*/
@IntrinsicCandidate publicstaticfloat fma(float a, float b, float c) { if (Float.isFinite(a) && Float.isFinite(b) && Float.isFinite(c)) { if (a == 0.0 || b == 0.0) { return a * b + c; // Handled signed zero cases
} else { return (new BigDecimal((double)a * (double)b) // Exact multiply
.add(new BigDecimal((double)c))) // Exact sum
.floatValue(); // One rounding // to a float value
}
} else { // At least one of a,b, and c is non-finite. The result // will be non-finite as well and will be the same // non-finite value under double as float arithmetic. return (float)fma((double)a, (double)b, (double)c);
}
}
// magnitude of a power of two so large that scaling a finite // nonzero value by it would be guaranteed to over or // underflow; due to rounding, scaling down takes an // additional power of two which is reflected here finalint MAX_SCALE = Double.MAX_EXPONENT + -Double.MIN_EXPONENT +
DoubleConsts.SIGNIFICAND_WIDTH + 1; int exp_adjust = 0; int scale_increment = 0; double exp_delta = Double.NaN;
// Make sure scaling factor is in a reasonable range
/** *Returns{@codef}×2<sup>{@codescaleFactor}</sup> *roundedasifperformedbyasinglecorrectlyrounded *floating-pointmultiply.Iftheexponentoftheresultis *between{@linkFloat#MIN_EXPONENT}and{@link *Float#MAX_EXPONENT},theansweriscalculatedexactly.Ifthe *exponentoftheresultwouldbelargerthan{@code *Float.MAX_EXPONENT},aninfinityisreturned.Notethatifthe *resultissubnormal,precisionmaybelost;thatis,when *{@codescalb(x,n)}issubnormal,{@codescalb(scalb(x,n), *-n)}maynotequal<i>x</i>.Whentheresultisnon-NaN,the *resulthasthesamesignas{@codef}. * *<p>Specialcases: *<ul> *<li>IfthefirstargumentisNaN,NaNisreturned. *<li>Ifthefirstargumentisinfinite,thenaninfinityofthe *samesignisreturned. *<li>Ifthefirstargumentiszero,thenazeroofthesame *signisreturned. *</ul> * *@apiNoteThismethodcorrespondstothescaleBoperation *definedinIEEE754. * *@paramfnumbertobescaledbyapoweroftwo. *@paramscaleFactorpowerof2usedtoscale{@codef} *@return{@codef}×2<sup>{@codescaleFactor}</sup> *@since1.6
*/ publicstaticfloat scalb(float f, int scaleFactor) { // magnitude of a power of two so large that scaling a finite // nonzero value by it would be guaranteed to over or // underflow; due to rounding, scaling down takes an // additional power of two which is reflected here finalint MAX_SCALE = Float.MAX_EXPONENT + -Float.MIN_EXPONENT +
FloatConsts.SIGNIFICAND_WIDTH + 1;
// Make sure scaling factor is in a reasonable range
scaleFactor = Math.max(Math.min(scaleFactor, MAX_SCALE), -MAX_SCALE);
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.243Bemerkung:
(vorverarbeitet am 2026-06-11)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.