Enhanced C#
Language of your choice: library documentation
|
This class helps generic code to perform calculations on numbers of unknown type, by providing access to various math interfaces. More...
This class helps generic code to perform calculations on numbers of unknown type, by providing access to various math interfaces.
T | A numeric type. |
If a certain math interface is not available for a certain type, then the corresponding field will be null. For example, Maths<int>.FloatMath is null because int is not floating-point. The Traits, Math, and related properties will be null for non-numeric types.
TODO: support non-builtin types!
Generic code that uses Maths<T> is slower than code that uses a generic parameter with a math constraint. That's because generic struct parameters are early-bound and can be inlined, while calls through an interface such as IMath<T> are normal late-bound interface calls and cannot be inlined. Compare the two examples below.
// Calculates the length of a vector with magnitude (x, y): // Slower version based on Maths<T>. Example: Length(3.0,4.0) public T Length<T>(T x, T y) { var m = Maths<T>.Math; return m.Sqrt(m.Add(m.Square(x), m.Square(y))); }
// Calculates the length of a vector with magnitude (x, y): // Faster version based on Maths<T>. Unfortunately, this version is // inconvenient to call because the caller must specify which math // provider to use. Example: Length<double,MathD>(3.0,4.0) public T Length<T,M>(T x, T y) where M:struct,IMath<T> { var m = default(M); return m.Sqrt(m.Add(m.Square(x), m.Square(y))); }