Scoop API

scoop:scoop.math:0.1.0

src/big_decimal/big_decimal.scoop

Selected production source · src/big_decimal/big_decimal.scoop

1package scoop.math
3/**
4 * An immutable arbitrary-precision decimal, coefficient * 10^(-scale). Equality and hashing
5 * compare numerical values, ignoring scale; sameRepresentation compares stored representations.
6 */
7public class BigDecimal internal constructor(
8 private val coefficient: IntegerStorage,
9 /** The decimal scale; negative scales represent integer powers of ten. */
10 public val scale: Long
11) : Equals<BigDecimal>, Compare<BigDecimal>, Hash, ToString,
12 Add<BigDecimal, BigDecimal>, Sub<BigDecimal, BigDecimal>, Mul<BigDecimal, BigDecimal>,
13 Div<BigDecimal, BigDecimal>, Rem<BigDecimal, BigDecimal>, UnaryPlus<BigDecimal>,
14 UnaryMinus<BigDecimal>, Increment<BigDecimal>, Decrement<BigDecimal> {
15 /** Constructs an exact signed integer with scale zero. */
16 public constructor(value: Long) : this(IntegerStorage.Small(value), 0L) {}
17 /** Constructs an exact unsigned integer with scale zero. */
18 public constructor(value: ULong) : this(integerUnsigned(value), 0L) {}
19 /** Shares the immutable integer coefficient at the requested scale. */
20 public constructor(unscaledValue: BigInteger, scale: Long = 0L) : this(unscaledValue.integerStorage(), scale) {}
21 /** Constructs a signed coefficient at the requested scale. */
22 public constructor(unscaledValue: Long, scale: Long) : this(IntegerStorage.Small(unscaledValue), scale) {}
24 internal fun decimalValue(): DecimalValue = DecimalValue(coefficient, decimalScale(scale))
25 /** The mathematical sign: -1, 0, or 1. */
26 public val signum: Int get() = integerSign(coefficient)
27 /** Returns the immutable signed coefficient, without applying the scale. */
28 public fun unscaledValue(): BigInteger = BigInteger(coefficient)
29 /** Returns the coefficient's decimal digit count, with precision one for zero. */
30 public fun precision(): Long = decimalPrecision(coefficient)
31 /** Returns one unit in the last stored place, at this scale. */
32 public fun ulp(): BigDecimal = BigDecimal(1L, scale)
33 /** Compares mathematical values; scale and redundant trailing zeros do not affect equality. */
34 public override operator fun equals(other: BigDecimal): Boolean = compareTo(other) == 0L
35 /** Orders mathematical values, returning -1, 0, or 1 without expanding large scale gaps. */
36 public override operator fun compareTo(other: BigDecimal): Long = decimalCompare(decimalValue(), other.decimalValue())
37 /** Hashes the mathematical value, consistently across all equivalent representations. */
38 public override fun hash(): Long = decimalHash(decimalValue())
39 /** Compares both the coefficient and scale. */
40 public fun sameRepresentation(other: BigDecimal): Boolean = scale == other.scale && integerCompare(coefficient, other.coefficient) == 0L
41 /** Returns the canonical decimal text, preserving the coefficient and scale on parsing. */
42 public override fun toString(): String = decimalString(decimalValue(), false)
43 /** Formats without an exponent; parsing preserves the numeric value. */
44 public fun toPlainString(): String = decimalPlain(decimalValue())
45 /** Uses an exponent divisible by three when scientific notation is needed. */
46 public fun toEngineeringString(): String = decimalString(decimalValue(), true)
48 /** Returns the exact sum at the larger operand scale. */
49 public override operator fun plus(other: BigDecimal): BigDecimal = decimalResult(decimalAddExact(decimalValue(), other.decimalValue()))
50 /** Returns the exact difference at the larger operand scale. */
51 public override operator fun minus(other: BigDecimal): BigDecimal = decimalResult(decimalAddExact(decimalValue(), decimalNegate(other.decimalValue())))
52 /** Returns the exact product at the sum of operand scales. */
53 public override operator fun times(other: BigDecimal): BigDecimal = decimalResult(decimalMultiply(decimalValue(), other.decimalValue()))
54 /** Returns the exact finite decimal quotient; zero division or a nonterminating result throws. */
55 public override operator fun div(other: BigDecimal): BigDecimal = decimalResult(decimalDivideExact(decimalValue(), other.decimalValue()))
56 /** Returns the exact remainder after division toward zero; a zero divisor throws. */
57 public override operator fun rem(other: BigDecimal): BigDecimal = divideAndRemainder(other)._2
58 /** Retains this immutable representation. */
59 public override operator fun unaryPlus(): BigDecimal = this
60 /** Negates the coefficient, preserving scale. */
61 public override operator fun unaryMinus(): BigDecimal = BigDecimal(integerNegate(coefficient), scale)
62 /** Returns this value plus the scale-zero constant one. */
63 public override operator fun inc(): BigDecimal = this + BigDecimal.ONE
64 /** Returns this value minus the scale-zero constant one. */
65 public override operator fun dec(): BigDecimal = this - BigDecimal.ONE
66 /** Returns the absolute value, preserving scale. */
67 public fun abs(): BigDecimal = if (signum < 0) -this else this
68 /** Returns the smaller value, retaining this instance on numeric equality. */
69 public fun min(other: BigDecimal): BigDecimal = if (this <= other) this else other
70 /** Returns the larger value, retaining this instance on numeric equality. */
71 public fun max(other: BigDecimal): BigDecimal = if (this >= other) this else other
73 /** Rounds the mathematical sum once to the explicit significant-digit context. */
74 public fun plus(other: BigDecimal, context: MathContext): BigDecimal {
75 requireMathContext(context)
76 return decimalResult(decimalAdd(decimalValue(), other.decimalValue(), context))
77 }
78 /** Rounds the mathematical difference once to the explicit context. */
79 public fun minus(other: BigDecimal, context: MathContext): BigDecimal {
80 requireMathContext(context)
81 return decimalResult(decimalAdd(decimalValue(), decimalNegate(other.decimalValue()), context))
82 }
83 /** Rounds the mathematical product once to the explicit context. */
84 public fun times(other: BigDecimal, context: MathContext): BigDecimal {
85 requireMathContext(context)
86 return decimalResult(decimalRound(decimalMultiply(decimalValue(), other.decimalValue()), context))
87 }
88 /** Divides using explicit significant digits; unlimited precision requires a finite exact result. */
89 public fun div(other: BigDecimal, context: MathContext): BigDecimal {
90 requireMathContext(context)
91 return decimalResult(decimalDivide(decimalValue(), other.decimalValue(), context, decimalScale(scale).minus(other.scale)))
92 }
93 /** Divides at the requested fixed scale, using the explicit rounding mode. */
94 public fun div(other: BigDecimal, scale: Long, roundingMode: RoundingMode): BigDecimal = decimalResult(decimalDivideAtScale(decimalValue(), other.decimalValue(), decimalScale(scale), roundingMode)._1)
95 /** Rounds once to the requested significant digits; negative precision is invalid. */
96 public fun round(context: MathContext): BigDecimal {
97 requireMathContext(context)
98 return decimalResult(decimalRound(decimalValue(), context))
99 }
100 /** Returns the integral quotient toward zero; finite precision must represent it exactly. */
101 public fun divideToIntegralValue(other: BigDecimal, context: MathContext = MathContext.Unlimited): BigDecimal {
102 requireMathContext(context)
103 return decimalResult(decimalIntegral(decimalValue(), other.decimalValue(), context))
104 }
105 /** Returns the integral quotient and exact remainder; the context limits only the quotient. */
106 public fun divideAndRemainder(other: BigDecimal, context: MathContext = MathContext.Unlimited): (BigDecimal, BigDecimal) {
107 requireMathContext(context)
108 val quotient = decimalResult(decimalIntegral(decimalValue(), other.decimalValue(), context))
109 val remainder = decimalResult(decimalAddExact(decimalValue(), decimalNegate(decimalMultiply(quotient.decimalValue(), other.decimalValue()))))
110 return (quotient, remainder)
111 }
112 /** Returns the exact remainder; the context limits only the integral quotient. */
113 public fun rem(other: BigDecimal, context: MathContext): BigDecimal {
114 requireMathContext(context)
115 val quotient = decimalIntegral(decimalValue(), other.decimalValue(), context)
116 quotient.scale.checked()
117 return decimalResult(decimalAddExact(decimalValue(), decimalNegate(decimalMultiply(quotient, other.decimalValue()))))
118 }
119 /** Returns an exact nonnegative integer power; 0^0 is one and negative exponents throw. */
120 public fun pow(exponent: Long): BigDecimal = decimalResult(decimalPow(decimalValue(), scale, exponent, MathContext.Unlimited))
121 /** Rounds the exact power once; finite precision also permits negative exponents. */
122 public fun pow(exponent: Long, context: MathContext): BigDecimal {
123 requireMathContext(context)
124 return decimalResult(decimalPow(decimalValue(), scale, exponent, context))
125 }
126 /** Rounds the mathematical square root once; unlimited precision requires a finite exact root. */
127 public fun sqrt(context: MathContext = MathContext.Unlimited): BigDecimal {
128 requireMathContext(context)
129 return decimalResult(decimalSqrt(decimalValue(), context))
130 }
132 /** Rescales exactly or rounds explicitly; the default rejects a nonzero discarded fraction. */
133 public fun setScale(scale: Long, roundingMode: RoundingMode = RoundingMode.Unnecessary): BigDecimal = decimalResult(decimalAtScale(decimalValue(), decimalScale(scale), roundingMode))
134 /** Multiplies exactly by a power of ten without changing the coefficient. */
135 public fun scaleByPowerOfTen(exponent: Long): BigDecimal = decimalResult(DecimalValue(coefficient, decimalScale(scale).minus(exponent)))
136 /** Moves the point left and clamps the resulting scale to at least zero. */
137 public fun movePointLeft(distance: Long): BigDecimal {
138 val moved = decimalScale(scale).plus(distance)
139 return decimalResult(decimalAtScale(DecimalValue(coefficient, moved), decimalScaleMax(moved, decimalScale(0L)), RoundingMode.Unnecessary))
140 }
141 /** Moves the point right and clamps the resulting scale to at least zero. */
142 public fun movePointRight(distance: Long): BigDecimal {
143 val moved = decimalScale(scale).minus(distance)
144 return decimalResult(decimalAtScale(DecimalValue(coefficient, moved), decimalScaleMax(moved, decimalScale(0L)), RoundingMode.Unnecessary))
145 }
146 /** Removes decimal coefficient zeros; zero becomes ZERO, and an unrepresentable nonzero scale throws. */
147 public fun stripTrailingZeros(): BigDecimal = decimalResult(decimalStrip(decimalValue(), None))
148 /** Truncates toward zero and returns an immutable integer. */
149 public fun toBigInteger(): BigInteger = BigInteger(decimalInteger(decimalValue(), false))
150 /** Converts only if there is no fractional part; otherwise throws ArithmeticException. */
151 public fun toBigIntegerExact(): BigInteger = BigInteger(decimalInteger(decimalValue(), true))
152 /** Rounds directly to binary32, allowing infinity and signed underflow zero. */
153 public fun toFloat(): Float = decimalFloat(decimalValue())
154 /** Rounds directly to binary64, allowing infinity and signed underflow zero. */
155 public fun toDouble(): Double = decimalDouble(decimalValue())
156 /** Truncates toward zero and retains the target integer's low bits. */
157 public fun toByte(): Byte = decimalLowBits(decimalValue()).toByte()
158 /** Requires both an integral value and a representable Byte; otherwise throws ArithmeticException. */
159 public fun toByteExact(): Byte = integerLowBits(decimalIntegerExactInRange(decimalValue(), IntegerStorage.Small(Byte.MIN_VALUE.toLong()), IntegerStorage.Small(Byte.MAX_VALUE.toLong()))).toByte()
160 /** Truncates toward zero and retains the target integer's low bits. */
161 public fun toShort(): Short = decimalLowBits(decimalValue()).toShort()
162 /** Requires both an integral value and a representable Short; otherwise throws ArithmeticException. */
163 public fun toShortExact(): Short = integerLowBits(decimalIntegerExactInRange(decimalValue(), IntegerStorage.Small(Short.MIN_VALUE.toLong()), IntegerStorage.Small(Short.MAX_VALUE.toLong()))).toShort()
164 /** Truncates toward zero and retains the target integer's low bits. */
165 public fun toInt(): Int = decimalLowBits(decimalValue()).toInt()
166 /** Requires both an integral value and a representable Int; otherwise throws ArithmeticException. */
167 public fun toIntExact(): Int = integerLowBits(decimalIntegerExactInRange(decimalValue(), IntegerStorage.Small(Int.MIN_VALUE.toLong()), IntegerStorage.Small(Int.MAX_VALUE.toLong()))).toInt()
168 /** Truncates toward zero and retains the target integer's low bits. */
169 public fun toLong(): Long = decimalLowBits(decimalValue()).toLong()
170 /** Requires both an integral value and a representable Long; otherwise throws ArithmeticException. */
171 public fun toLongExact(): Long = integerLowBits(decimalIntegerExactInRange(decimalValue(), IntegerStorage.Small(Long.MIN_VALUE.toLong()), IntegerStorage.Small(Long.MAX_VALUE.toLong()))).toLong()
172 /** Truncates toward zero and retains the target integer's low bits. */
173 public fun toUByte(): UByte = decimalLowBits(decimalValue()).toUByte()
174 /** Requires both an integral value and a representable UByte; otherwise throws ArithmeticException. */
175 public fun toUByteExact(): UByte = integerLowBits(decimalIntegerExactInRange(decimalValue(), IntegerStorage.Small(0L), IntegerStorage.Small(UByte.MAX_VALUE.toLong()))).toUByte()
176 /** Truncates toward zero and retains the target integer's low bits. */
177 public fun toUShort(): UShort = decimalLowBits(decimalValue()).toUShort()
178 /** Requires both an integral value and a representable UShort; otherwise throws ArithmeticException. */
179 public fun toUShortExact(): UShort = integerLowBits(decimalIntegerExactInRange(decimalValue(), IntegerStorage.Small(0L), IntegerStorage.Small(UShort.MAX_VALUE.toLong()))).toUShort()
180 /** Truncates toward zero and retains the target integer's low bits. */
181 public fun toUInt(): UInt = decimalLowBits(decimalValue()).toUInt()
182 /** Requires both an integral value and a representable UInt; otherwise throws ArithmeticException. */
183 public fun toUIntExact(): UInt = integerLowBits(decimalIntegerExactInRange(decimalValue(), IntegerStorage.Small(0L), IntegerStorage.Small(UInt.MAX_VALUE.toLong()))).toUInt()
184 /** Truncates toward zero and retains the target integer's low bits. */
185 public fun toULong(): ULong = decimalLowBits(decimalValue()).toULong()
186 /** Requires both an integral value and a representable ULong; otherwise throws ArithmeticException. */
187 public fun toULongExact(): ULong = integerLowBits(decimalIntegerExactInRange(decimalValue(), IntegerStorage.Small(0L), integerUnsigned(ULong.MAX_VALUE))).toULong()
189 /** Constants and explicit decimal construction. */
190 public companion object {
191 /** Zero at scale zero. */
192 public val ZERO: BigDecimal = BigDecimal(0L)
193 /** One at scale zero. */
194 public val ONE: BigDecimal = BigDecimal(1L)
195 /** Two at scale zero. */
196 public val TWO: BigDecimal = BigDecimal(2L)
197 /** Ten at scale zero. */
198 public val TEN: BigDecimal = BigDecimal(10L)
199 /** Parses ASCII decimal text with an optional exponent, preserving trailing zeros. */
200 public fun parse(text: String): BigDecimal = decimalResult(decimalRequireParsed(text))
201 /** Returns None for malformed text or an unrepresentable parsed scale. */
202 public fun parseOrNone(text: String): BigDecimal? = when (decimalParse(text)) {
203 case Some(val value) -> Some(decimalResult(value))
204 case None -> None
205 }
206 /** Parses the finite binary32 value's shortest round-trip decimal text. */
207 public fun fromFloat(value: Float): BigDecimal {
208 if (!value.isFinite()) throw IllegalArgumentException(Some("nonfinite decimal input"))
209 return parse(value.toString())
210 }
211 /** Parses the finite binary64 value's shortest round-trip decimal text. */
212 public fun fromDouble(value: Double): BigDecimal {
213 if (!value.isFinite()) throw IllegalArgumentException(Some("nonfinite decimal input"))
214 return parse(value.toString())
215 }
216 /** Expands the exact finite binary32 value, removing unnecessary fractional zeros. */
217 public fun fromFloatExact(value: Float): BigDecimal = decimalResult(decimalFromFloat(value))
218 /** Expands the exact finite binary64 value, removing unnecessary fractional zeros. */
219 public fun fromDoubleExact(value: Double): BigDecimal = decimalResult(decimalFromDouble(value))
220 }
223internal fun decimalResult(value: DecimalValue): BigDecimal = BigDecimal(value.coefficient, value.scale.checked())