add method
- FloatingPointValue a,
- FloatingPointValue b, {
- FloatingPointRoundingMode roundingMode = FloatingPointRoundingMode.roundNearestEven,
Adds a and b exactly and rounds once into this format.
Implementation
FpvType add(FloatingPointValue a, FloatingPointValue b,
{FloatingPointRoundingMode roundingMode =
FloatingPointRoundingMode.roundNearestEven}) {
if (a.isNaN | b.isNaN) {
return _propagateNaN(a, b);
}
if (a.isAnInfinity | b.isAnInfinity) {
if (a.isAnInfinity && b.isAnInfinity && a.sign != b.sign) {
return nan;
}
final infinity = a.isAnInfinity ? a : b;
return _infinityOrLargestFinite(
negative: infinity.sign.toBool(), roundingMode: roundingMode);
}
final aExact = _decodeFinite(a);
final bExact = _decodeFinite(b);
final commonExponent = min(aExact.exponent, bExact.exponent);
final aSigned =
(a.sign.toBool() ? -aExact.significand : aExact.significand) <<
(aExact.exponent - commonExponent);
final bSigned =
(b.sign.toBool() ? -bExact.significand : bExact.significand) <<
(bExact.exponent - commonExponent);
final sum = aSigned + bSigned;
final sameSignZeros =
a.isAZero && b.isAZero && a.sign.toBool() == b.sign.toBool();
final negative = sum.isNegative ||
(sum == BigInt.zero &&
(sameSignZeros
? a.sign.toBool()
: roundingMode ==
FloatingPointRoundingMode.roundTowardsNegativeInfinity));
return _quantize((significand: sum.abs(), exponent: commonExponent),
negative: negative, roundingMode: roundingMode);
}