BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News .NET 7 Adds Generic Math

.NET 7 Adds Generic Math

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

For example, one could write a function that calculated the standard deviation for a list of singles. Then that same function could be reused for doubles and halves instead of duplicating it.

It could also be used for a units of measure library. One could write new Length<int>(5) instead of having a different meter type for every underlying numeric type the caller may desire. 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 mathematical interfaces is actually much more comprehensive than just addition and subtraction. Here is 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.

About the Author

Rate this Article

Adoption
Style

BT