Boost Your .NET Projects with Spargine: MathExtensions for Numeric Spans, Percentage Changes, and Rounding

Spargine is a collection of open-source assemblies and NuGet packages designed for .NET 10, which I have been developing and maintaining since the release of .NET Framework 2. These assemblies are not only a core part of my projects but are also actively deployed in production environments across several companies I collaborate with.

Get Spargine

You can access the source code and NuGet packages here:

When I’m working with a buffer of benchmark measurements, I often want the total, the average, or the fastest and slowest times. The MathExtensions class in DotNetTips.Spargine.Extensions lets me calculate those values directly on a ReadOnlySpan<T>. The methods work with a range of numeric types through .NET’s generic math interfaces, and MinMax() finds both extremes in a single pass.

The class also extends individual values with helpers for percentage change, rounding, primality testing, and basic arithmetic. Here’s what each method does and where the input type affects the result.

Working with Numeric Spans

Average<T>()

Adds the values and divides by the number of elements. The result has the same type as the elements, so an int span containing 2 and 3 returns 2. The sum is also calculated in T, which means it can overflow for fixed-width integer types. An empty span is rejected.

FindMax<T>() and FindMin<T>()

Return the largest and smallest values, respectively. Both require a nonempty span. For floating-point inputs, a NaN element propagates to the result.

MinMax<T>()

Returns a named tuple, (Min, Max), after scanning the span once. It’s handy when you need both ends of a range, such as the fastest and slowest benchmark measurements. It requires a nonempty span, and a NaN element produces NaN for both results.

Sum<T>()

Adds the values in the span and returns the result in the element type. An empty span returns the type’s additive identity, which is zero for standard numeric types. Fixed-width integer sums can overflow.

Working with Individual Values

Add(int add) and Subtract(int subtract)

Perform arithmetic on an int and return a double. The arithmetic itself takes place as int before the result is converted.

CalculatePercent(second)

Calculates the signed percentage change from the first value to the second, using the absolute value of the first as the baseline. Overloads accept double, int, long, and TimeSpan. The int and long overloads divide before converting to double, so 100.CalculatePercent(125) returns 0, while 100.0.CalculatePercent(125.0) returns 25. For a zero baseline, the integer overloads throw, while the double and TimeSpan overloads produce infinity or NaN.

IsPrime()

Checks whether an int is prime. It handles values below 2 and multiples of 2 or 3 early, then checks possible divisors in pairs up to the square root.

Round()

Extends double and decimal with overloads that accept a digit count, a MidpointRounding mode, or both. Every overload returns an int. The parameterless double overload rounds toward positive infinity, so 2.1 becomes 3. The parameterless decimal overload rounds to the nearest integer, with ties going to the even integer. Overloads that take a digit count round at that precision first, then convert the result to int.

Summary

The span methods are the additions I’ll reach for most. Sum() and Average() cover the usual totals and averages, and MinMax() gets both extremes without scanning the same data twice. The type you choose matters most when you need a fractional average or percentage change. For rounding, check the overload as well, since every Round() method returns a whole number.

Get Involved!

The success of open-source projects like Spargine relies on community contributions. If you find these updates useful or have ideas for further improvements, I encourage you to contribute by:

  • Submitting pull requests
  • Reporting issues
  • Suggesting new features

Your input is invaluable in making Spargine an even more powerful tool for the .NET community.

If you are interested in contributing or have any questions, feel free to contact me via email at dotnetdave@live.com. Your support and collaboration are greatly appreciated!

Thank you, and happy coding!

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copyrighted and cannot be reproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a Reply