public static HNumber DivRem(HNumber left, HNumber right, out HNumber remainder) { //Remainder = Numerator - Quotient x Denominator if (right.IsZero) { throw new DivideByZeroException("The Divisor is zero"); } int precision = Math.Max(left.Precision, right.Precision); #region Division Again But with higher precision HNumber tmpLeft = left; int digitDiff = tmpLeft.Precision - (tmpLeft.DigitCount - right.DigitCount); digitDiff = Math.Max(0, digitDiff); tmpLeft.Mantissa *= BigInteger.Pow(10, digitDiff); tmpLeft.Truncate(tmpLeft.DigitCount + tmpLeft.Exponent); BigInteger mantissa = BigInteger.Divide(tmpLeft.Mantissa, right.Mantissa); int exponent = tmpLeft.Exponent - right.Exponent - digitDiff; HNumber quotient = new HNumber(mantissa, exponent, CalculateDigitCount(mantissa), RoundingMode.PrecisionInt); #endregion HNumber qd = Multiply(quotient, right, PrecisionMode.KeepPrecision); remainder = Subtract(left, qd); remainder.Precision = precision; remainder.Round(RoundingMode.PrecisionInt); return(quotient); }
public static HNumber Add(HNumber left, HNumber right, PrecisionMode precisionMode = PrecisionMode.UseHigher) { int precision = DEFAULT_PRECISION; if (precisionMode == PrecisionMode.UseHigher) { precision = Math.Max(left.Precision, right.Precision); } else if (precisionMode == PrecisionMode.UseLesser) { precision = Math.Min(left.Precision, right.Precision); } //TODO: ONLY WHEN SEMI ACCURATE RESULTS ARE REQUIRED int digitsTotal = left.DigitCount + right.DigitCount; left.Precision = digitsTotal; right.Precision = digitsTotal; left.Round(RoundingMode.PrecisionInt); right.Round(RoundingMode.PrecisionInt); if (left.Exponent < right.Exponent) { left.Truncate(left.DigitCount - (right.Exponent - left.Exponent)); } else if (left.Exponent > right.Exponent) { right.Truncate(right.DigitCount - (left.Exponent - right.Exponent)); } BigInteger mantissa = left.Mantissa + right.Mantissa; int exponent = Math.Max(left.Exponent, right.Exponent); if (precisionMode == PrecisionMode.KeepPrecision) { precision = CalculateDigitCount(mantissa); } HNumber result = new HNumber(mantissa, exponent, precision); return(result); }