Microsoft

.NET 7 adds general math

In our last article we introduced generic parsing. This was a springboard to the real goal, generic math. Since the introduction of .NET 2 in 2005, developers have been asking for an interface that supports basic arithmetic operations such as addition and subtraction. This would allow them to build more complex mathematical libraries without having to specify a particular type.

For example, you could write a function that calculates the standard deviation for a list of singles. Then that same function could be reused for doubling and halving instead of duplicating it.

It can also be used for a unit of measurement library. One could write new Length<int>(5) instead of having a different meter type for each underlying numerical type the caller desires. To illustrate this, here is a theoretical division operator for length and duration.


public static Velocity<T> operator /(Length<T> length, Duration<T> duration)
{
    return new Velocity<T>(length.Value / duration.Value);
}

The actual list of generic math interfaces is actually much more extensive than just addition and subtraction. Here’s an example for double.


IAdditionOperators<double,double,double>
IAdditiveIdentity<double,double>
IBinaryFloatingPointIeee754<double>
IBinaryNumber<double>
IBitwiseOperators<double,double,double>
IComparisonOperators<double,double,bool>
IDecrementOperators<double>
IDivisionOperators<double,double,double>
IEqualityOperators<double,double,bool>
IExponentialFunctions<double>
IFloatingPoint<double>
IFloatingPointConstants<double>
IFloatingPointIeee754<double>
IHyperbolicFunctions<double>
IIncrementOperators<double>
ILogarithmicFunctions<double>
IMinMaxValue<double>
IModulusOperators<double,double,double>
IMultiplicativeIdentity<double,double>
IMultiplyOperators<double,double,double>
INumber<double>
INumberBase<double>
IPowerFunctions<double>
IRootFunctions<double>
ISignedNumber<double>
ISubtractionOperators<double,double,double>
ITrigonometricFunctions<double>
IUnaryNegationOperators<double,double>
IUnaryPlusOperators<double,double>

You can find the complete list in the System.Numerics namespace.

Leave a Comment