Scoop API

scoop:scoop.math:0.1.0

src/internal/decimal/arithmetic.scoop

Selected production source · src/internal/decimal/arithmetic.scoop

1package scoop.math
3internal fun decimalAddExact(a: DecimalValue, b: DecimalValue): DecimalValue {
4 val scale = decimalScaleMax(a.scale, b.scale)
5 return DecimalValue(integerAdd(decimalScaleCoefficient(a.coefficient, scale.minus(a.scale)), decimalScaleCoefficient(b.coefficient, scale.minus(b.scale))), scale)
6}
8internal fun decimalMultiply(a: DecimalValue, b: DecimalValue): DecimalValue = DecimalValue(integerMultiply(a.coefficient, b.coefficient), a.scale.plus(b.scale))
10internal fun decimalAdd(a: DecimalValue, b: DecimalValue, context: MathContext): DecimalValue {
11 if (context.precision == 0L) return decimalAddExact(a, b)
12 val preferred = decimalScaleMax(a.scale, b.scale)
13 if (integerSign(a.coefficient) == 0) return decimalPreferExact(decimalRound(b, context), preferred, context.precision)
14 if (integerSign(b.coefficient) == 0) return decimalPreferExact(decimalRound(a, context), preferred, context.precision)
15 val leftAdjusted = decimalAdjusted(a)
16 val rightAdjusted = decimalAdjusted(b)
17 val distance = leftAdjusted.minus(rightAdjusted)
18 val guard = decimalScale(context.precision).plus(2L)
19 if (distance.compare(guard) > 0L) return decimalAddSeparated(a, b, context)
20 if (distance.negate().compare(guard) > 0L) return decimalAddSeparated(b, a, context)
21 return decimalRound(decimalAddExact(a, b), context)
24// The smaller operand lies below the two guard digits. Exact tail comparisons decide carries,
25// cancellation, and ties without materializing a power spanning the operands' scale gap.
26private fun decimalAddSeparated(large: DecimalValue, small: DecimalValue, context: MathContext): DecimalValue {
27 val sign = integerSign(large.coefficient)
28 val magnitude = decimalAbs(large)
29 val tiny = decimalAbs(small)
30 val grid = decimalScale(context.precision).plus(1L).minus(decimalAdjusted(large))
31 val truncated = decimalAtScale(magnitude, grid, RoundingMode.Down)
32 val remainder = decimalAddExact(magnitude, decimalNegate(truncated))
33 var coefficient = truncated.coefficient
34 var sticky = true
35 if (sign == integerSign(small.coefficient)) {
36 val distance = decimalAddExact(DecimalValue(IntegerStorage.Small(1L), grid), decimalNegate(remainder))
37 val order = decimalCompare(tiny, distance)
38 if (order >= 0L) {
39 coefficient = integerAdd(coefficient, IntegerStorage.Small(1L))
40 sticky = order != 0L
41 }
42 } else {
43 val order = decimalCompare(remainder, tiny)
44 if (order < 0L) coefficient = integerSubtract(coefficient, IntegerStorage.Small(1L))
45 sticky = order != 0L
46 }
47 if (sign < 0) coefficient = integerNegate(coefficient)
48 return decimalRound(DecimalValue(coefficient, grid), context, sticky)