Class FixedPointArithmetic
Base- and precision-aware arithmetic for IFixedPointAmount, following the standard fixed-point algorithms (see https://en.wikipedia.org/wiki/Fixed-point_arithmetic).
public static class FixedPointArithmetic
- Inheritance
-
FixedPointArithmetic
- Inherited Members
Remarks
Addition and subtraction require a common scaling factor (same base and precision) and throw PrecisionMismatchException otherwise.
Multiplication and division support differing base and precision. Both take
an explicit resultBase and resultPrecision
so the caller owns the target scale; the result is rounded half away from
zero. The concrete result type is chosen by the generic parameter and its
base must match resultBase.
All intermediates use BigInteger; the final decomposition is checked against long (whole) and ulong (fraction) and throws OverflowException when it does not fit.
Methods
Add<T>(T, T)
Add two amounts of the same base and precision.
public static T Add<T>(T left, T right) where T : IFixedPointAmount<T>
Parameters
leftTrightT
Returns
- T
Type Parameters
T
Exceptions
- PrecisionMismatchException
Bases or precisions differ.
Divide<T>(IFixedPointAmount, IFixedPointAmount, int, int)
Divide left by right, expressing the
result at resultBase and resultPrecision.
public static T Divide<T>(IFixedPointAmount left, IFixedPointAmount right, int resultBase, int resultPrecision) where T : IFixedPointAmount<T>
Parameters
leftIFixedPointAmountrightIFixedPointAmountresultBaseintresultPrecisionint
Returns
- T
Type Parameters
T
Exceptions
- DivideByZeroException
rightis zero.- ArgumentException
resultBasedoes not matchT's base.
Multiply<T>(IFixedPointAmount, IFixedPointAmount, int, int)
Multiply two amounts, expressing the result at resultBase
and resultPrecision. Equivalent to
(left/Base_l^P_l) * (right/Base_r^P_r) rounded to the target scale.
public static T Multiply<T>(IFixedPointAmount left, IFixedPointAmount right, int resultBase, int resultPrecision) where T : IFixedPointAmount<T>
Parameters
leftIFixedPointAmountrightIFixedPointAmountresultBaseintresultPrecisionint
Returns
- T
Type Parameters
T
Exceptions
- ArgumentException
resultBasedoes not matchT's base.
Rescale<T>(IFixedPointAmount, int, int)
Convert amount to resultBase and
resultPrecision, rounding half away from zero.
public static T Rescale<T>(IFixedPointAmount amount, int resultBase, int resultPrecision) where T : IFixedPointAmount<T>
Parameters
amountIFixedPointAmountresultBaseintresultPrecisionint
Returns
- T
Type Parameters
T
Exceptions
- ArgumentException
resultBasedoes not matchT's base.
Subtract<T>(T, T)
Subtract two amounts of the same base and precision.
public static T Subtract<T>(T left, T right) where T : IFixedPointAmount<T>
Parameters
leftTrightT
Returns
- T
Type Parameters
T
Exceptions
- PrecisionMismatchException
Bases or precisions differ.