Module_Core - vorcyc/Vorcyc.Mathematics GitHub Wiki

Location: Home / Core module


Core module

This module provides basic mathematical operations, common functions, and extension methods, covering array operations, base conversion, bit operations, combinatorics, constant definitions, numeric mapping, pinnable arrays, random number generation, trigonometry, and various math functions.

All types below are in the namespace: Vorcyc.Mathematics (buffer types such as PinnableArray<T>, POHBuffer<T>, and NativeBuffer<T> are in Vorcyc.Mathematics.Buffers)

πŸ“’Contents


Vorcyc.Mathematics.ArrayExtension Class

The Vorcyc.Mathematics.ArrayExtension class provides extension methods for array operations, including splitting arrays (Split and Zip methods), copying, initializing, filling, random filling, extracting inner segments, removing segments, merging, converting to strings, fast fragment copying, repeating arrays, zero-padding, and getting the first and last elements of an array. These methods simplify and optimize common array workflows for a variety of scenarios.

Methods and descriptions

General methods

1. Copy

  • public static T[] Copy<T>(this T[] source)
    Copies the entire array.
  • public static T[] Copy<T>(this T[] source, int length)
    Copies the array up to the specified length.

2. InitializeArray

  • public static T[]? InitializeArray<T>(int length, T initialValue = default)
    Initializes an array of the specified length filled with the initial value.

3. Fill

  • public static void Fill<T>(this T[] array, T value)
    Fills the entire array with the specified value.
  • public static void Fill<T>(this T[] array, int start, int end, T value)
    Fills the specified range of the array with the specified value.
  • public static void Fill<T>(this T[] array, Range range, T value)
    Fills the specified range of the array with the specified value.
  • public static void Fill<T>(this Span<T> values, T value)
    Fills the specified Span<T>.

4. FillWithRandomNumber

  • public static void FillWithRandomNumber(this Span<float> span)
    Fills the span with random floating-point numbers.
  • public static void FillWithRandomNumber<T>(this T[] array) where T : IFloatingPointIeee754<T>
    Fills the array with random numbers.
  • public static void FillWithRandomNumber<T>(this T[] array, Range range) where T : IFloatingPointIeee754<T>
    Fills the specified range of the array with random numbers.
  • public static void FillWithRandomNumber(this int[] array, (int max, int min)? limit = null)
    Fills the array with random numbers.
  • public static void FillWithRandomNumber(this int[] array, Range range)
    Fills the specified range of the array with random numbers.
  • public static void FillWithRandomNumber(this long[] array)
    Fills the array with random numbers.
  • public static void FillWithRandomNumber(this long[] array, Range range)
    Fills the specified range of the array with random numbers.

5. GetInner

  • public static IEnumerable<T> GetInner<T>(this T[] array, int start, int length) Gets an inner segment of the array and returns an enumerable sequence.

6. GetInnerArray

  • public static T[] GetInnerArray<T>(this T[] array, int start, int length) Gets an inner segment of the array and returns a new array.

7. RemoveSegment

  • public static T[] RemoveSegment<T>(this T[] array, int start, int length) Removes a segment from the array and returns a new array.

8. Merge

  • public static T[] Merge<T>(this T[] leading, T[] following) Merges two arrays and returns the combined array.

9. ToString

  • public static string ToString<T>(this IEnumerable<T> collection) Converts the collection to its string representation.

10. FastCopyFragment

  • public static T[] FastCopyFragment<T>(this T[] source, int size, int sourceOffset = 0, int destinationOffset = 0) where T : unmanaged
    Quickly copies a fragment of the array into a new array.

11. FastCopyTo

  • public static void FastCopyTo<T>(this T[] source, T[] destination, int size, int sourceOffset = 0, int destinationOffset = 0)
    Quickly copies elements from one array to another.

12. Repeat

  • public static T[] Repeat<T>(this T[] source, int n)
    Creates a new array containing the source array repeated the specified number of times.

Single-precision methods

13. FastCopy

  • public static float[] FastCopy(this float[] source) Creates a fast copy of a single-precision floating-point array.

14. FastCopyTo

  • public static void FastCopyTo(this float[] source, float[] destination, int size, int sourceOffset = 0, int destinationOffset = 0)
    Quickly copies elements from one single-precision array to another.

15. FastCopyFragment

  • public static float[] FastCopyFragment(this float[] source, int size, int sourceOffset = 0, int destinationOffset = 0)
    Quickly copies a fragment of a single-precision array into a new array.

16. Merge

  • public static float[] Merge(this float[] source, float[] another)
    Merges two single-precision arrays and returns the combined array.

17. Repeat

public static float[] Repeat(this float[] source, int n) Creates a new array containing the source single-precision array repeated the specified number of times.

18. PadZeros

  • public static float[] PadZeros(this float[] source, int size)
    Zero-pads the array to the target length, creating a single-precision array of the specified size.
  • public static T[] PadZeros<T>(this T[] source, int size)
    Zero-pads the array to the target length, creating an array of the specified size.

Double-precision methods

19. FastCopy

  • public static double[] FastCopy(this double[] source)
    Creates a fast copy of a double-precision floating-point array.

20. FastCopyTo

  • public static void FastCopyTo(this double[] source, double[] destination, int size, int sourceOffset = 0, int destinationOffset = 0)
    Quickly copies elements from one double-precision array to another.

21. FastCopyFragment

  • public static double[] FastCopyFragment(this double[] source, int size, int sourceOffset = 0, int destinationOffset = 0)
    Quickly copies a fragment of a double-precision array into a new array.

22. Merge

  • public static double[] Merge(this double[] source, double[] another)
    Merges two double-precision arrays and returns the combined array.

23. Repeat

  • public static double[] Repeat(this double[] source, int n)
    Creates a new array containing the source double-precision array repeated the specified number of times.

24. PadZeros

  • public static double[] PadZeros(this double[] source, int size)
    Creates a zero-padded double-precision array of the specified size.

Other methods

25. ToFloats

  • public static float[] ToFloats(this IEnumerable<double> values)
    Converts an enumerable of double-precision values to a single-precision array.

26. ToDoubles

  • public static double[] ToDoubles(this IEnumerable<float> values)
    Converts an enumerable of single-precision values to a double-precision array.

27. Last

  • public static T Last<T>(this T[] array)
    Gets the last element of the array.

28. First

  • public static T First<T>(this T[] array)
    Gets the first element of the array.

Code Example

using System;
using System.Linq;
using Vorcyc.Mathematics;

public class ArrayExtensionExample
{
	public static void Main()
	{
		// Create an integer array
		int[] array = { 1, 2, 3, 4, 5 };

		// Copy the array
		int[] copiedArray = array.Copy();
		Console.WriteLine("Copied Array: " + string.Join(", ", copiedArray));

		// Initialize an array of length 5 with initial value 10
		int[] initializedArray = ArrayExtension.InitializeArray(5, 10);
		Console.WriteLine("Initialized Array: " + string.Join(", ", initializedArray));

		// Fill the array with a specified value
		array.Fill(9);
		Console.WriteLine("Filled Array: " + string.Join(", ", array));

		// Fill the array with random numbers
		array.FillWithRandomNumber((max: 100, min: 1));
		Console.WriteLine("Array Filled with Random Numbers: " + string.Join(", ", array));

		// Get an inner segment of the array
		int[] innerArray = array.GetInnerArray(1, 3);
		Console.WriteLine("Inner Array: " + string.Join(", ", innerArray));

		// Remove a segment from the array
		int[] removedSegmentArray = array.RemoveSegment(1, 2);
		Console.WriteLine("Array after Removing Segment: " + string.Join(", ", removedSegmentArray));

		// Merge two arrays
		int[] mergedArray = array.Merge(new int[] { 6, 7, 8 });
		Console.WriteLine("Merged Array: " + string.Join(", ", mergedArray));

		// Convert the array to a string
		string arrayString = array.ToString();
		Console.WriteLine("Array as String: " + arrayString);

		// Quickly copy a fragment of the array
		int[] fastCopiedFragment = array.FastCopyFragment(3, 1);
		Console.WriteLine("Fast Copied Fragment: " + string.Join(", ", fastCopiedFragment));

		// Create a new array with the source repeated 3 times
		int[] repeatedArray = array.Repeat(3);
		Console.WriteLine("Repeated Array: " + string.Join(", ", repeatedArray));

		// Split the array into segments of the specified length
		var segments = array.Split(2);
		Console.WriteLine("Array Segments:");
		foreach (var segment in segments)
		{
			Console.WriteLine(string.Join(", ", segment));
		}

		// Zip the array into a sequence of segments
		var zippedSegments = array.Zip(3);
		Console.WriteLine("Zipped Array Segments:");
		foreach (var segment in zippedSegments)
		{
			Console.WriteLine(string.Join(", ", segment));
		}

		// Transform a single-precision array to a new array of the specified length by averaging segments
		float[] floatArray = { 1.1f, 2.2f, 3.3f, 4.4f, 5.5f };
		float[] transformedArray = floatArray.TransformToArray(3);
		Console.WriteLine("Transformed Array: " + string.Join(", ", transformedArray));
	}
}

Vorcyc.Mathematics.BaseConverter Class

Vorcyc.Mathematics.BaseConverter is a static class that converts integer types implementing IBinaryInteger<TSelf> to a string in a specified base, and converts strings in a specified base back to integers. The class provides the following main functionality:

Methods and descriptions

1. ToBaseString

  • public static string ToBaseString<TSelf>(this TSelf integer, TSelf baseNumber) where TSelf : IBinaryInteger<TSelf> Converts an integer type implementing IBinaryInteger<TSelf> to a string in the specified base. Valid bases range from 2 to 94.
  • Parameters:
    • integer: The integer to convert.
    • baseNumber: The base. Must be greater than or equal to 2 and less than or equal to 94.
  • Returns: The number as a string in the specified base.
  • Exceptions:
    1. ArgumentOutOfRangeException: Thrown when the integer is negative or the base is not between 2 and 94.

2. FromBaseString

  • public static TSelf FromBaseString<TSelf>(this string value, TSelf baseNumber) where TSelf : IBinaryInteger<TSelf>
  • Converts a string in the specified base to an integer type implementing IBinaryInteger<TSelf>. Valid bases range from 2 to 94.
  • Parameters:
    1. value: The string to convert.
    2. baseNumber: The base. Must be greater than or equal to 2 and less than or equal to 94.
  • Returns: The converted integer.
  • Exceptions:
    1. ArgumentOutOfRangeException: Thrown when the base is not between 2 and 94 or the string contains invalid characters.

Code Example

using System;
using Vorcyc.Mathematics;

public class BaseConverterExample
{
	public static void Main()
	{
		// Convert an integer to a string in the specified base
		int number = 100;
		int baseNumber = 16;
		// Use ToBaseString to convert integer 100 to base-16 string representation
		string baseString = number.ToBaseString(baseNumber);
		Console.WriteLine($"Number {number} in base {baseNumber} is: {baseString}");

		// Convert a string in the specified base to an integer
		string value = "64";
		// Use FromBaseString to convert base-16 string "64" to an integer
		int convertedNumber = value.FromBaseString(baseNumber);
		Console.WriteLine($"String {value} in base {baseNumber} is: {convertedNumber}");
	}
}

Vorcyc.Mathematics.BitMathExtension Class

Vorcyc.Mathematics.BitMathExtension is a static class that provides extension methods for bit operations. The class includes the following main functionality:

Methods and descriptions

1. IsPowerOf2

  • public static bool IsPowerOf2(this uint x)
  • public static bool IsPowerOf2(this ulong x)
  • public static bool IsPowerOf2(this int x)
  • public static bool IsPowerOf2(this long x)
  • Determines whether a value is a power of 2.

2. NextPowerOf2

  • public static int NextPowerOf2(this int x)
  • public static ulong NextPowerOf2(this ulong value)
  • public static uint NextPowerOf2(this uint value)
  • Gets the next power of 2.

3. PreviousPowerOf2

  • public static int PreviousPowerOf2(this int x)
  • public static ulong PreviousPowerOf2(this ulong value)
  • public static uint PreviousPowerOf2(this uint value)
  • Gets the previous power of 2.

4. CountBitsSet

  • public static int CountBitsSet(this uint value)
  • public static int CountBitsSet(this ulong value)
  • Counts the number of set bits.

5. CountBitsCleared

  • public static int CountBitsCleared(this uint value)
  • public static int CountBitsCleared(this ulong value)
  • Counts the number of cleared bits.

6. CreateBitMask

  • public static ulong CreateBitMask(this int bitCount)
  • Creates a bit mask with the given number of bits.

7. CountTrailingZeros

  • public static int CountTrailingZeros(this uint value)
  • public static int CountTrailingZeros(this ulong value)
  • Counts the number of consecutive zeros starting from the least significant bit.

8. CountLeadingZeros

  • public static int CountLeadingZeros(this uint value)
  • public static int CountLeadingZeros(this ulong value)
  • Counts the number of consecutive zeros starting from the most significant bit.

9. CountTrailingOnes

  • public static int CountTrailingOnes(this uint value)
  • public static int CountTrailingOnes(this ulong value)
  • Counts the number of consecutive ones starting from the least significant bit.

10. CountLeadingOnes

  • public static int CountLeadingOnes(this uint value)
  • public static int CountLeadingOnes(this ulong value)
  • Counts the number of consecutive ones starting from the most significant bit.

11. GetSetBitPositions

  • public static IEnumerable<int> GetSetBitPositions(this ulong value)
  • public static IEnumerable<int> GetSetBitPositions(this uint value)
  • Returns the positions of set bits.

12. GetClearedBitPositions

  • public static IEnumerable<int> GetClearedBitPositions(this uint value)
  • public static IEnumerable<int> GetClearedBitPositions(this ulong value)
  • Returns the positions of cleared bits.

13. IsOdd

  • public static bool IsOdd(this long value)
  • public static bool IsOdd(this ulong value)
  • public static bool IsOdd(this int value)
  • public static bool IsOdd(this uint value)
  • Determines whether the value is odd.

14. IsEven

  • public static bool IsEven(this long value)
  • public static bool IsEven(this ulong value)
  • public static bool IsEven(this int value)
  • public static bool IsEven(this uint value)
  • Determines whether the value is even.

Code Example

The following example uses several methods from the BitMathExtension class, with comments included:

using System;
using Vorcyc.Mathematics;

public class BitMathExtensionExample
{
	public static void Main()
	{
		// Determine whether a value is a power of 2
		int number = 16;
		bool isPowerOf2 = number.IsPowerOf2();
		Console.WriteLine($"{number} is power of 2: {isPowerOf2}");

		// Get the next power of 2
		int nextPowerOf2 = number.NextPowerOf2();
		Console.WriteLine($"Next power of 2 after {number} is: {nextPowerOf2}");

		// Get the previous power of 2
		int previousPowerOf2 = number.PreviousPowerOf2();
		Console.WriteLine($"Previous power of 2 before {number} is: {previousPowerOf2}");

		// Count set bits
		uint value = 29;
		int bitsSet = value.CountBitsSet();
		Console.WriteLine($"Number of bits set in {value} is: {bitsSet}");

		// Count cleared bits
		int bitsCleared = value.CountBitsCleared();
		Console.WriteLine($"Number of bits cleared in {value} is: {bitsCleared}");

		// Create a bit mask with the given number of bits
		int bitCount = 5;
		ulong bitMask = bitCount.CreateBitMask();
		Console.WriteLine($"Bit mask with {bitCount} bits is: {bitMask}");

		// Count trailing zeros
		int trailingZeros = value.CountTrailingZeros();
		Console.WriteLine($"Number of trailing zeros in {value} is: {trailingZeros}");

		// Count leading zeros
		int leadingZeros = value.CountLeadingZeros();
		Console.WriteLine($"Number of leading zeros in {value} is: {leadingZeros}");

		// Determine whether the value is odd
		bool isOdd = number.IsOdd();
		Console.WriteLine($"{number} is odd: {isOdd}");

		// Determine whether the value is even
		bool isEven = number.IsEven();
		Console.WriteLine($"{number} is even: {isEven}");
	}
}

Vorcyc.Mathematics.Combinatorics Class

Vorcyc.Mathematics.Combinatorics is a static class that provides combinatorial functions. The class includes the following main functionality:

Methods and descriptions

1. TruthTable

  • public static int[][] TruthTable(int length)
  • public static int[][] TruthTable(int symbols, int length)
  • public static int[][] TruthTable(this int[] symbols)
  • Generates all possible ordered arrangements with repetition (truth table).

2. Sequences

  • public static IEnumerable<int[]> Sequences(int length, bool inPlace = false)
  • public static IEnumerable<int[]> Sequences(int symbols, int length, bool inPlace = false)
  • public static IEnumerable<int[]> Sequences(this int[] symbols, bool inPlace = false)
  • Enumerates all possible ordered arrangements with repetition (truth table) without large memory allocations.

3. Combinations

  • public static IEnumerable<T[]> Combinations<T>(this T[] values, bool inPlace = false)
  • public static IEnumerable<T[]> Combinations<T>(this T[] values, int k, bool inPlace = false)
  • Enumerates all possible combinations of values from the given array.

4. Subsets

  • public static IEnumerable<SortedSet<T>> Subsets<T>(this ISet<T> set, bool inPlace = false)
  • public static IEnumerable<SortedSet<T>> Subsets<T>(this ISet<T> set, int k, bool inPlace = false)
  • Generates all possible subsets of the given set.

Code Example

The following example uses several methods from the Combinatorics class, with comments included:

using System;
using System.Collections.Generic;
using Vorcyc.Mathematics;

public class CombinatoricsExample
{
	public static void Main()
	{
		// Generate a truth table
		int length = 3;
		int[][] truthTable = Combinatorics.TruthTable(length);
		Console.WriteLine("Truth Table:");
		foreach (var row in truthTable)
		{
			Console.WriteLine(string.Join(", ", row));
		}

		// Enumerate all possible ordered arrangements
		Console.WriteLine("\nSequences:");
		foreach (var sequence in Combinatorics.Sequences(length))
		{
			Console.WriteLine(string.Join(", ", sequence));
		}

		// Enumerate all possible combinations of values from the array
		int[] values = { 1, 2, 3 };
		Console.WriteLine("\nCombinations:");
		foreach (var combination in Combinatorics.Combinations(values))
		{
			Console.WriteLine(string.Join(", ", combination));
		}

		// Generate all possible subsets of the set
		ISet<int> set = new HashSet<int> { 1, 2, 3 };
		Console.WriteLine("\nSubsets:");
		foreach (var subset in Combinatorics.Subsets(set))
		{
			Console.WriteLine(string.Join(", ", subset));
		}
	}
}

Vorcyc.Mathematics.ConstantsFp32 Class

Vorcyc.Mathematics.ConstantsFp32 is a static class that defines commonly used single-precision floating-point constants. These constants are useful in mathematical computation. Each constant is described below:

Constants and descriptions

1. E

  • public const float E = 2.71828182845904523536f;
  • The base of the natural logarithm, e.

2. LOG2E

  • public const float LOG2E = 1.44269504088896340736f;
  • The base-2 logarithm of e.

3. LOG10E

  • public const float LOG10E = 0.434294481903251827651f;
  • The base-10 logarithm of e.

4. LN2

  • public const float LN2 = 0.693147180559945309417f;
  • The natural logarithm of 2.

5. LN10

  • public const float LN10 = 2.30258509299404568402f;
  • The natural logarithm of 10.

6. PI

  • public const float PI = 3.1415926535897932384626433832795f;
  • Pi (Ο€).

7. PI_2

  • public const float PI_2 = 1.57079632679489661923f;
  • Half of Ο€.

8. PI_4

  • public const float PI_4 = 0.785398163397448309616f;
  • One quarter of Ο€.

9. _1_PI

  • public const float _1_PI = 0.318309886183790671538f;
  • 1 divided by Ο€.

10. _2_PI

  • public const float _2_PI = 0.636619772367581343076f;
  • 2 divided by Ο€.

11. _2_SQRT_PI

  • public const float _2_SQRT_PI = 1.12837916709551257390f;
  • 2 divided by the square root of Ο€.

12. _SQRT2

  • public const float _SQRT2 = 1.41421356237309504880f;
  • The square root of 2.

13. _SQRT1_2

  • public const float _SQRT1_2 = 0.707106781186547524401f;
  • 1 divided by the square root of 2.

14. TWO_PI

  • public const float TWO_PI = 6.28318530717958647692f;
  • 2 times Ο€.

15. TOLERANCE

  • public const float TOLERANCE = 1E-09f;
  • Tolerance used when comparing floating-point values.

16. RADIANS_PER_DEGREE

  • public const float RADIANS_PER_DEGREE = 0.01745329f;
  • Radians per degree.

17. DEGREES_PER_RADIAN

  • public const float DEGREES_PER_RADIAN = 57.29578f;
  • Degrees per radian.

18. EPSILON

  • public const float EPSILON = 0.001f;
  • A small value used for floating-point comparison.

Code Example

The following example uses constants from the ConstantsFp32 class, with comments included:

using System;
using Vorcyc.Mathematics;

public class ConstantsFp32Example
{
	public static void Main()
	{
		// Use the base of the natural logarithm, e
		float e = ConstantsFp32.E;
		Console.WriteLine($"e: {e}");

		// Use pi (Ο€)
		float pi = ConstantsFp32.PI;
		Console.WriteLine($"Ο€: {pi}");

		// Use radians per degree
		float radiansPerDegree = ConstantsFp32.RADIANS_PER_DEGREE;
		Console.WriteLine($"Radians per degree: {radiansPerDegree}");

		// Use degrees per radian
		float degreesPerRadian = ConstantsFp32.DEGREES_PER_RADIAN;
		Console.WriteLine($"Degrees per radian: {degreesPerRadian}");

		// Use tolerance
		float tolerance = ConstantsFp32.TOLERANCE;
		Console.WriteLine($"Tolerance: {tolerance}");

		// Use epsilon
		float epsilon = ConstantsFp32.EPSILON;
		Console.WriteLine($"Epsilon: {epsilon}");
	}
}

Vorcyc.Mathematics.NumberMapper Class

Vorcyc.Mathematics.NumberMapper is a static class that maps a value from one range to another. The class includes the following main functionality:

Methods and descriptions

1. Map

  • Maps an input value from one range to another.
  • public static TNumber Map<TNumber>(this TNumber number, TNumber inMin, TNumber inMax, TNumber outMin, TNumber outMax, InputValueOutOfRangeHandleBehavior handleBehavior = InputValueOutOfRangeHandleBehavior.Saturating) where TNumber : unmanaged, INumber<TNumber>
    • Parameters:
      1. number: The input value to map.
      2. inMin: Minimum value of the input range.
      3. inMax: Maximum value of the input range.
      4. outMin: Minimum value of the output range.
      5. outMax: Maximum value of the output range.
      6. handleBehavior: Behavior when the input value is out of range. Default is InputValueOutOfRangeHandleBehavior.Saturating.
    • Returns: The value mapped to the output range.
    • Exceptions:
      1. ArgumentOutOfRangeException: Thrown when inMin is greater than or equal to inMax, or outMin is greater than or equal to outMax.
      2. ArgumentException: Thrown when number is outside the input range and handleBehavior is InputValueOutOfRangeHandleBehavior.ThrowException.

2. Map

  • Maps a floating-point value from one range to another and returns a Boolean indicating success.
  • public static bool Map<TFloatingNumber>(TFloatingNumber input, TFloatingNumber inputMin, TFloatingNumber inputMax, TFloatingNumber outputMin, TFloatingNumber outputMax, out TFloatingNumber result) where TFloatingNumber : unmanaged, IFloatingPointIeee754<TFloatingNumber>
    • Parameters:
      1. input: The floating-point value to map.
      2. inputMin: Minimum value of the input range.
      3. inputMax: Maximum value of the input range.
      4. outputMin: Minimum value of the output range.
      5. outputMax: Maximum value of the output range.
      6. result: The mapped floating-point value if successful; otherwise NaN.
    • Returns: true if mapping succeeded; otherwise false.

3. Enums

- `InputValueOutOfRangeHandleBehavior`
- Defines behavior when the input value is outside the specified range. Values:
	1. `Saturating`: Clamps the input value to the nearest boundary.
	2. `ThrowException`: Throws an exception when the input value is out of range.

Code Example

The following example uses methods from the NumberMapper class, with comments included:

using System;
using Vorcyc.Mathematics;

public class NumberMapperExample
{
	public static void Main()
	{
		// Map an integer from one range to another
		int number = 5;
		int inMin = 0;
		int inMax = 10;
		int outMin = 0;
		int outMax = 100;
		int mappedValue = number.Map(inMin, inMax, outMin, outMax);
		Console.WriteLine($"Mapped value: {mappedValue}");

		// Map a floating-point value from one range to another and return success
		float input = 0.5f;
		float inputMin = 0.0f;
		float inputMax = 1.0f;
		float outputMin = 0.0f;
		float outputMax = 100.0f;
		bool success = NumberMapper.Map(input, inputMin, inputMax, outputMin, outputMax, out float result);
		Console.WriteLine($"Mapping successful: {success}, Mapped value: {result}");
	}
}

Vorcyc.Mathematics.Buffers.PinnableArray<T> Class

Vorcyc.Mathematics.Buffers.PinnableArray<T> is a generic class representing a one-dimensional array with optional memory pinning for high-performance access and array operations. The class provides methods and properties for array manipulation and can pin memory for interop with unmanaged code. The class includes the following main functionality:

Methods and descriptions

1. Constructors

  • public PinnableArray(int length, bool pin = true) Initializes a PinnableArray instance with the specified length (length must be β‰₯ 1).
  • public PinnableArray(ReadOnlyMemory<T> memory, bool pin = true) Initializes a PinnableArray instance from a read-only memory block.
  • public PinnableArray(ReadOnlySpan<T> span, bool pin = true) Initializes a PinnableArray instance from a read-only span.
  • public PinnableArray(ArraySegment<T> segment, bool pin = true) Initializes a PinnableArray instance from an ArraySegment<T>.
  • public PinnableArray(T[] array, bool pin = true) Initializes a PinnableArray instance from an array.
  • public PinnableArray(T[] array, int offset, int length, bool pin = true) Initializes a PinnableArray instance from a portion of an array.

2. Pin

  • public void Pin() Pins the PinnableArray in memory for interop with unmanaged code.

3. Unpin

  • public void Unpin() Unpins the PinnableArray so it can be garbage-collected.

4. Fill

  • public void Fill(T value) Fills the entire array with the specified value.
  • public void Fill(T startValue, T step) Fills the array using the specified start value and step.
  • public void FillWith<TNumber>(TNumber number) where TNumber : unmanaged Fills the array with a value of another unmanaged type.

5. Max

Extension methods provided by PinnableArrayExtension (requires T : IFloatingPointIeee754<T>, so not available for int).

  • public T Max() Returns the maximum value in the array.
  • public T Max(int start, int length) Returns the maximum value in the specified range.
  • public async Task<T> MaxAsync(int? numberOfWorkers = null, bool useTPL = false) Asynchronously returns the maximum value in the array.
  • public async Task<T> MaxAsync(int start, int length, int? numberOfWorkers = null, bool useTPL = false) Asynchronously returns the maximum value in the specified range.

6. Min

Extension methods provided by PinnableArrayExtension (requires T : IFloatingPointIeee754<T>, so not available for int).

  • public T Min() Returns the minimum value in the array.
  • public T Min(int start, int length) Returns the minimum value in the specified range.
  • public async Task<T> MinAsync(int? numberOfWorkers = null, bool useTPL = false) Asynchronously returns the minimum value in the array. Uses parallel execution for better performance on large arrays.
  • public async Task<T> MinAsync(int start, int length, int? numberOfWorkers = null, bool useTPL = false) Asynchronously returns the minimum value in the specified range. Uses parallel execution for better performance on large arrays.

7. Dispose

  • public void Dispose() Releases resources held by the PinnableArray.

Properties

8. IsPinned

  • public bool IsPinned { get; } Gets whether the array is currently pinned in memory.

9. Length

  • public int Length { get; } Gets the length of the array.

10. Values

  • public T[] Values { get; } Gets the array as a standard T[].

Code Example

The following example uses several methods from the PinnableArray class, with comments included:

using System;
using System.Threading.Tasks;
using Vorcyc.Mathematics;
using Vorcyc.Mathematics.Buffers;

public class PinnableArrayExample
{
	public static async Task Main()
	{
		// Initialize a PinnableArray from an array (defaults to pin: true)
		float[] array = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };
		PinnableArray<float> pinnableArray = new PinnableArray<float>(array);

		// Pin the array in memory
		pinnableArray.Pin();
		Console.WriteLine($"IsPinned: {pinnableArray.IsPinned}");

		// Get the array length
		int length = pinnableArray.Length;
		Console.WriteLine($"Length: {length}");

		// Get the array as a standard T[] (implicit conversion)
		float[] values = pinnableArray;
		Console.WriteLine($"Values: {string.Join(", ", values)}");

		// Fill the entire array with a specified value
		pinnableArray.Fill(10.0f);
		Console.WriteLine($"Filled Values: {string.Join(", ", pinnableArray.Values)}");

		// Fill the array with a start value and step
		pinnableArray.Fill(1.0f, 2.0f);
		Console.WriteLine($"Filled with step Values: {string.Join(", ", pinnableArray.Values)}");

		// Access and modify elements via the indexer
		pinnableArray[0] = 42.0f;
		Console.WriteLine($"First element after modification: {pinnableArray[0]}");

		// Get a Span representation of the array via the Span property
		Span<float> span = pinnableArray.Span;
		Console.WriteLine($"Span values: {string.Join(", ", span.ToArray())}");

		// Get the maximum value (extension method, requires IFloatingPointIeee754<T>)
		float maxValue = pinnableArray.Max();
		Console.WriteLine($"Max value: {maxValue}");

		// Get the minimum value (extension method, requires IFloatingPointIeee754<T>)
		float minValue = pinnableArray.Min();
		Console.WriteLine($"Min value: {minValue}");

		// Asynchronously get the maximum value
		float maxAsyncValue = await pinnableArray.MaxAsync();
		Console.WriteLine($"Max async value: {maxAsyncValue}");

		// Asynchronously get the minimum value
		float minAsyncValue = await pinnableArray.MinAsync();
		Console.WriteLine($"Min async value: {minAsyncValue}");

		// Unpin the array
		pinnableArray.Unpin();
		Console.WriteLine($"IsPinned: {pinnableArray.IsPinned}");

		// Release resources
		pinnableArray.Dispose();
	}
}

SimpleRNG_Fp32 and SimpleRNG_Fp64 Classes

Vorcyc.Mathematics.SimpleRNG_Fp32 and Vorcyc.Mathematics.SimpleRNG_Fp64 are static classes for generating 32-bit and 64-bit floating-point random numbers, respectively. They are based on George Marsaglia's MWC (multiply-with-carry) algorithm and produce random numbers that pass Marsaglia's DIEHARD tests.

Methods and descriptions

1. SetSeed

  • public static void SetSeed(uint u, uint v)

    • Sets the random number generator seed.
    • Parameters:
      • u: First seed value.
      • v: Second seed value.
  • public static void SetSeed(uint u)

    • Sets the random number generator seed.
    • Parameters:
      • u: Seed value.
  • public static void SetSeedFromSystemTime()

    • Seeds the random number generator from system time.

2. GetUniform

  • public static double GetUniform()
    • Generates a uniformly distributed random number in the interval (0, 1).

3. GetNormal

  • public static double GetNormal()

    • Generates a normally distributed random number with mean 0 and standard deviation 1.
  • public static double GetNormal(double mean, double standardDeviation)

    • Generates a normally distributed random number with the specified mean and standard deviation.
    • Parameters:
      • mean: Mean.
      • standardDeviation: Standard deviation.

4. GetExponential

  • public static double GetExponential()

    • Generates an exponentially distributed random number with mean 1.
  • public static double GetExponential(double mean)

    • Generates an exponentially distributed random number with the specified mean.
    • Parameters:
      • mean: Mean.

5. GetGamma

  • public static double GetGamma(double shape, double scale)
    • Generates a gamma-distributed random number with the specified shape and scale parameters.
    • Parameters:
      • shape: Shape parameter.
      • scale: Scale parameter.

6. GetChiSquare

  • public static double GetChiSquare(double degreesOfFreedom)
    • Generates a chi-square distributed random number with the specified degrees of freedom.
    • Parameters:
      • degreesOfFreedom: Degrees of freedom.

7. GetInverseGamma

  • public static double GetInverseGamma(double shape, double scale)
    • Generates an inverse-gamma distributed random number with the specified shape and scale parameters.
    • Parameters:
      • shape: Shape parameter.
      • scale: Scale parameter.

8. GetWeibull

  • public static double GetWeibull(double shape, double scale)
    • Generates a Weibull-distributed random number with the specified shape and scale parameters.
    • Parameters:
      • shape: Shape parameter.
      • scale: Scale parameter.

9. GetCauchy

  • public static double GetCauchy(double median, double scale)
    • Generates a Cauchy-distributed random number with the specified median and scale parameters.
    • Parameters:
      • median: Median.
      • scale: Scale parameter.

10. GetStudentT

  • public static double GetStudentT(double degreesOfFreedom)
    • Generates a Student's t-distributed random number with the specified degrees of freedom.
    • Parameters:
      • degreesOfFreedom: Degrees of freedom.

11. GetLaplace

  • public static double GetLaplace(double mean, double scale)
    • Generates a Laplace (double exponential) distributed random number with the specified mean and scale parameters.
    • Parameters:
      • mean: Mean.
      • scale: Scale parameter.

12. GetLogNormal

  • public static double GetLogNormal(double mu, double sigma)
    • Generates a log-normal distributed random number.
    • Parameters:
      • mu: Mean of the log-normal distribution.
      • sigma: Standard deviation of the log-normal distribution.

13. GetBeta

  • public static double GetBeta(double a, double b)
    • Generates a beta-distributed random number with the specified parameters.
    • Parameters:
      • a: First beta distribution parameter.
      • b: Second beta distribution parameter.

Code Example

The following example uses several methods from the SimpleRNG_Fp32 and SimpleRNG_Fp64 classes, with comments included:

using System;
using Vorcyc.Mathematics;

public class SimpleRNGExample
{
	public static void Main()
	{
		// Generate random numbers with SimpleRNG_Fp64
		SimpleRNG_Fp64.SetSeedFromSystemTime();
		double uniform64 = SimpleRNG_Fp64.GetUniform();
		double normal64 = SimpleRNG_Fp64.GetNormal();
		double exponential64 = SimpleRNG_Fp64.GetExponential();
		double gamma64 = SimpleRNG_Fp64.GetGamma(2.0, 2.0);
		double chiSquare64 = SimpleRNG_Fp64.GetChiSquare(2.0);
		double inverseGamma64 = SimpleRNG_Fp64.GetInverseGamma(2.0, 2.0);
		double weibull64 = SimpleRNG_Fp64.GetWeibull(2.0, 2.0);
		double cauchy64 = SimpleRNG_Fp64.GetCauchy(0.0, 1.0);
		double studentT64 = SimpleRNG_Fp64.GetStudentT(2.0);
		double laplace64 = SimpleRNG_Fp64.GetLaplace(0.0, 1.0);
		double logNormal64 = SimpleRNG_Fp64.GetLogNormal(0.0, 1.0);
		double beta64 = SimpleRNG_Fp64.GetBeta(2.0, 2.0);

		Console.WriteLine("SimpleRNG_Fp64:");
		Console.WriteLine($"Uniform: {uniform64}");
		Console.WriteLine($"Normal: {normal64}");
		Console.WriteLine($"Exponential: {exponential64}");
		Console.WriteLine($"Gamma: {gamma64}");
		Console.WriteLine($"ChiSquare: {chiSquare64}");
		Console.WriteLine($"InverseGamma: {inverseGamma64}");
		Console.WriteLine($"Weibull: {weibull64}");
		Console.WriteLine($"Cauchy: {cauchy64}");
		Console.WriteLine($"StudentT: {studentT64}");
		Console.WriteLine($"Laplace: {laplace64}");
		Console.WriteLine($"LogNormal: {logNormal64}");
		Console.WriteLine($"Beta: {beta64}");

		// Generate random numbers with SimpleRNG_Fp32
		SimpleRNG_Fp32.SetSeedFromSystemTime();
		float uniform32 = SimpleRNG_Fp32.GetUniform();
		float normal32 = SimpleRNG_Fp32.GetNormal();
		float exponential32 = SimpleRNG_Fp32.GetExponential();
		float gamma32 = SimpleRNG_Fp32.GetGamma(2.0f, 2.0f);
		float chiSquare32 = SimpleRNG_Fp32.GetChiSquare(2.0f);
		float inverseGamma32 = SimpleRNG_Fp32.GetInverseGamma(2.0f, 2.0f);
		float weibull32 = SimpleRNG_Fp32.GetWeibull(2.0f, 2.0f);
		float cauchy32 = SimpleRNG_Fp32.GetCauchy(0.0f, 1.0f);
		float studentT32 = SimpleRNG_Fp32.GetStudentT(2.0f);
		float laplace32 = SimpleRNG_Fp32.GetLaplace(0.0f, 1.0f);
		float logNormal32 = SimpleRNG_Fp32.GetLogNormal(0.0f, 1.0f);
		float beta32 = SimpleRNG_Fp32.GetBeta(2.0f, 2.0f);

		Console.WriteLine("SimpleRNG_Fp32:");
		Console.WriteLine($"Uniform: {uniform32}");
		Console.WriteLine($"Normal: {normal32}");
		Console.WriteLine($"Exponential: {exponential32}");
		Console.WriteLine($"Gamma: {gamma32}");
		Console.WriteLine($"ChiSquare: {chiSquare32}");
		Console.WriteLine($"InverseGamma: {inverseGamma32}");
		Console.WriteLine($"Weibull: {weibull32}");
		Console.WriteLine($"Cauchy: {cauchy32}");
		Console.WriteLine($"StudentT: {studentT32}");
		Console.WriteLine($"Laplace: {laplace32}");
		Console.WriteLine($"LogNormal: {logNormal32}");
		Console.WriteLine($"Beta: {beta32}");
	}
}

Vorcyc.Mathematics.TrigonometryHelper Class

Vorcyc.Mathematics.TrigonometryHelper is a static class that provides helper methods for trigonometric operations. The class includes the following main functionality:

Methods and descriptions

1. RadiansToDegrees

public static double RadiansToDegrees(double a)
public static float RadiansToDegrees(float radians)
Converts an angle from radians to degrees.

2. DegreesToRadians

public static double DegreesToRadians(double a)
public static float DegreesToRadians(float degrees)
Converts an angle from degrees to radians.

3. GetAngleDifference

public static float GetAngleDifference(float radianAngle1, float radianAngle2)
Gets the difference between two angles in radians.

4. RadianMin

public static float RadianMin(float radianAngle) public static double RadianMin(double radianAngle) Reduces an angle to its equivalent value in the range [-Ο€, Ο€].

5. Angle

public static float Angle(float x, float y)
public static double Angle(double x, double y)
Gets the angle formed by the vector [x, y] in radians.

6. Acosh

public static double Acosh(double x)
public static float Acosh(float x)
Returns the inverse hyperbolic cosine of the specified value.

7. Asinh

public static double Asinh(double d)
public static float Asinh(float d)
public static T Asinh<T>(T x) where T : struct, IFloatingPointIeee754<T>
Returns the inverse hyperbolic sine of the specified value.

8. Atanh

public static double Atanh(double d)
public static float Atanh(float d)
Returns the inverse hyperbolic tangent of the specified value.

9. Sinc

public static double Sinc(double x)
public static float Sinc(float x)
public static T Sinc<T>(T x) where T : IFloatingPointIeee754<T>
Computes the sinc function.

Code Example

The following example uses several methods from the TrigonometryHelper class, with comments included:

using System;
using Vorcyc.Mathematics;

public class TrigonometryHelperExample
{
	public static void Main()
	{
		// Convert an angle from radians to degrees
		double radians = Math.PI;
		double degrees = TrigonometryHelper.RadiansToDegrees(radians);
		Console.WriteLine($"Radians: {radians}, Degrees: {degrees}");

		// Convert an angle from degrees to radians
		degrees = 180.0;
		radians = TrigonometryHelper.DegreesToRadians(degrees);
		Console.WriteLine($"Degrees: {degrees}, Radians: {radians}");

		// Get the difference between two angles in radians
		float angle1 = 1.0f;
		float angle2 = 2.0f;
		float angleDifference = TrigonometryHelper.GetAngleDifference(angle1, angle2);
		Console.WriteLine($"Angle1: {angle1}, Angle2: {angle2}, Difference: {angleDifference}");

		// Reduce an angle to the range [-Ο€, Ο€]
		float radianAngle = 4.0f;
		float reducedAngle = TrigonometryHelper.RadianMin(radianAngle);
		Console.WriteLine($"Radian Angle: {radianAngle}, Reduced Angle: {reducedAngle}");

		// Get the angle formed by vector [x, y] in radians
		float x = 1.0f;
		float y = 1.0f;
		float vectorAngle = TrigonometryHelper.Angle(x, y);
		Console.WriteLine($"Vector [x,y]: [{x},{y}], Angle: {vectorAngle}");

		// Return the inverse hyperbolic cosine of the specified value
		double value = 2.0;
		double acoshValue = TrigonometryHelper.Acosh(value);
		Console.WriteLine($"Value: {value}, Acosh: {acoshValue}");

		// Return the inverse hyperbolic sine of the specified value
		value = 1.0;
		double asinhValue = TrigonometryHelper.Asinh(value);
		Console.WriteLine($"Value: {value}, Asinh: {asinhValue}");

		// Return the inverse hyperbolic tangent of the specified value
		value = 0.5;
		double atanhValue = TrigonometryHelper.Atanh(value);
		Console.WriteLine($"Value: {value}, Atanh: {atanhValue}");

		// Compute the sinc function
		double sincValue = TrigonometryHelper.Sinc(value);
		Console.WriteLine($"Sinc({value}) = {sincValue}");
	}
}

Vorcyc.Mathematics.VMath Class

Vorcyc.Mathematics.VMath is a static class that provides a variety of mathematical functions and operations. The class includes the following main functionality:

Methods and descriptions

1. BinomialCoefficient

public static float BinomialCoefficient(int k, int n)
Computes the binomial coefficient.

2. Diff

public static void Diff(float[] samples, float[] diff)
Computes the discrete difference.

3. InterpolateLinear

public static void InterpolateLinear(float[] x, float[] y, float[] arg, float[] interp)
Performs linear interpolation. Requires at least two knots (x.Length >= 2) and y.Length >= x.Length; otherwise throws ArgumentException.

4. BilinearTransform

public static void BilinearTransform(double[] re, double[] im)
public static void BilinearTransform(float[] re, float[] im)
Applies the bilinear transform.

5. Unwrap

public static double[] Unwrap(double[] phase, double tolerance = Math.PI)
public static float[] Unwrap(float[] phase, float tolerance = ConstantsFp32.PI)
public static T[] Unwrap<T>(T[] phase, T? tolerance = null) where T : unmanaged, IFloatingPointIeee754<T>
Unwraps phase values.

6. Wrap

public static double[] Wrap(double[] phase, double tolerance = Math.PI)
public static float[] Wrap(float[] phase, float tolerance = ConstantsFp32.PI)
Wraps phase values.

7. FindNth

public static float FindNth(float[] a, int n, int start, int end)
public static T FindNth<T>(Span<T> values, int n) where T : INumber<T>
Finds the nth order statistic in an array. n must lie in [start, end] (array overload) or [0, values.Length - 1] (span overload); otherwise throws ArgumentOutOfRangeException (it used to loop forever).

8. I0

public static double I0(double x)
public static float I0(float x)
public static T I0<T>(T x) where T : IFloatingPointIeee754<T>
public static Complex<T> I0<T>(Complex<T> x) where T : struct, INumberBase<T>, IFloatingPointIeee754<T>, IMinMaxValue<T>
Computes the modified Bessel function of the first kind, I0.

9. PolynomialRoots

public static Complex[]? PolynomialRoots(double[] a, int maxIterations = PolyRootsIterations)
public static ComplexFp32[]? PolynomialRoots(float[] a, int maxIterations = PolyRootsIterations)
Computes the complex roots of a polynomial using the Durand-Kerner algorithm.

10. EvaluatePolynomial

public static Complex EvaluatePolynomial(double[] a, Complex x)
public static ComplexFp32 EvaluatePolynomial(float[] a, ComplexFp32 x)
Evaluates a polynomial using Horner's method.

11. MultiplyPolynomials

public static Complex[] MultiplyPolynomials(Complex[] poly1, Complex[] poly2)
public static ComplexFp32[] MultiplyPolynomials(ComplexFp32[] poly1, ComplexFp32[] poly2)
Multiplies two polynomials.

12. DividePolynomial

public static Complex[][] DividePolynomial(Complex[] dividend, Complex[] divisor)
public static ComplexFp32[][] DividePolynomial(ComplexFp32[] dividend, ComplexFp32[] divisor)
Divides one polynomial by another.

13. Gcd

public static int Gcd(int n, int m)
public static T Gcd<T>(this T a, T b) where T : IBinaryInteger<T>
Computes the greatest common divisor (GCD) of two integers using the Euclidean algorithm.

14. Hcf

public static int Hcf(int a, int b)
Computes the highest common factor (HCF) of two integers with the iterative Euclidean algorithm. The result is non-negative and Hcf(0, 0) == 0.

15. Lcm

public static int Lcm(int a, int b)
Computes the least common multiple (LCM) of two integers. Returns 0 when either argument is 0; the result is non-negative and computed without intermediate overflow (OverflowException only if the true LCM does not fit in int).

16. SimplestIntegerRatioOfFraction

public static (int numerator, int denominator) SimplestIntegerRatioOfFraction(int numerator, int denominator)
Reduces a fraction to its simplest integer ratio. The denominator of the result is positive; throws DivideByZeroException when the denominator is 0.

17. Hypotenuse

public static double Hypotenuse(double a, double b)
public static float Hypotenuse(float a, float b)
Computes the hypotenuse of a right triangle.

18. Mod

public static int Mod(int x, int m)
public static double Mod(double x, double m)
public static float Mod(float x, float m)
Computes the modulus of an integer or real number.

19. FactorialPower

public static int FactorialPower(int value, int degree)
Returns the factorial power of the specified value.

20. TruncatedPower

public static double TruncatedPower(double value, double degree)
Truncated power function.

21. InvSqrt

public static float InvSqrt(float f)
public static double InvSqrt(double f)
Fast inverse square root of a floating-point value.

22. Max

public static float Max(float a, float b, float c)
public static double Max(double a, double b, double c)
Returns the maximum of three values.

23. Min

public static float Min(float a, float b, float c)
public static double Min(double a, double b, double c)
Returns the minimum of three values.

24. Pow2

public static int Pow2(int power)
Computes a power of 2.

25. Log2

public static int Log2(int x)
public static T Log2<T>(int x) where T : IBinaryInteger<T>
Computes the base-2 logarithm.

26. Factorial

public static int Factorial(int n)
public static T Factorial<T>(T n) where T : INumber<T>
Computes the factorial.

27. Gamma

public static double Gamma(double x)
public static float Gamma(float x)
public static T Gamma<T>(T x) where T : IFloatingPointIeee754<T>
Computes the gamma function using an approximation.

28. GammaLog

public static double GammaLog(double x)
public static float GammaLog(float x)
public static T GammaLog<T>(T x) where T : IFloatingPointIeee754<T>
Computes the natural logarithm of the gamma function.

29. Erf

public static T Erf<T>(T x) where T : IFloatingPointIeee754<T>
Computes the error function.

30. LowerIncompleteGamma

public static T LowerIncompleteGamma<T>(T s, T x) where T : IFloatingPointIeee754<T>
Computes the lower incomplete gamma function using an approximation.

31. Beta

public static T Beta<T>(T alpha, T beta) where T : IFloatingPointIeee754<T>
Computes the beta function.

32. RegularizedIncompleteBeta

public static T RegularizedIncompleteBeta<T>(T x, T alpha, T beta) where T : IFloatingPointIeee754<T>
Computes the regularized incomplete beta function.

33. Sqrt

public static decimal Sqrt(decimal x, decimal epsilon = 0.0M)
Returns the square root of the specified decimal value.

34. Ulp

public static double Ulp(double value)
public static float Ulp(float value)
public static Half Ulp(Half value)
Computes the unit in the last place (ULP) of the input value.

Code Example

The following example uses several methods from the VMath class, with comments included:

using System;
using Vorcyc.Mathematics;

public class VMathExample
{
	public static void Main()
	{
		// Compute the binomial coefficient
		int k = 3; int n = 5;
		float binomialCoefficient = VMath.BinomialCoefficient(k, n);
		Console.WriteLine($"BinomialCoefficient({k}, {n}) = {binomialCoefficient}");

		// Compute the discrete difference
		float[] samples = { 1.0f, 2.0f, 4.0f, 7.0f };
		float[] diff = new float[samples.Length];
		VMath.Diff(samples, diff);
		Console.WriteLine($"Diff: {string.Join(", ", diff)}");

		// Perform linear interpolation
		float[] xValues = { 0.0f, 1.0f, 2.0f };
		float[] yValues = { 0.0f, 1.0f, 4.0f };
		float[] arg = { 0.5f, 1.5f };
		float[] interp = new float[arg.Length];
		VMath.InterpolateLinear(xValues, yValues, arg, interp);
		Console.WriteLine($"InterpolateLinear: {string.Join(", ", interp)}");

		// Apply the bilinear transform
		double[] re = { 0.5, 0.6 };
		double[] im = { 0.5, 0.6 };
		VMath.BilinearTransform(re, im);
		Console.WriteLine($"BilinearTransform: re = {string.Join(", ", re)}, im = {string.Join(", ", im)}");

		// Unwrap phase values
		double[] phase = { 0.0, Math.PI, 2 * Math.PI, 3 * Math.PI };
		double[] unwrappedPhase = VMath.Unwrap(phase);
		Console.WriteLine($"Unwrap: {string.Join(", ", unwrappedPhase)}");

		// Find the nth order statistic in an array
		float[] array = { 3.0f, 1.0f, 4.0f, 1.5f };
		float nthValue = VMath.FindNth(array, 2, 0, array.Length - 1);
		Console.WriteLine($"FindNth: {nthValue}");

		// Compute the modified Bessel function I0
		double x = 1.0;
		double i0Value = VMath.I0(x);
		Console.WriteLine($"I0({x}) = {i0Value}");

		// Compute polynomial roots using the Durand-Kerner algorithm
		double[] coefficients = { 1.0, -6.0, 11.0, -6.0 };
		var roots = VMath.PolynomialRoots(coefficients);
		Console.WriteLine($"PolynomialRoots: {string.Join(", ", roots)}");

		// Evaluate a polynomial
		var complexX = new Complex(1.0, 1.0);
		var polynomialValue = VMath.EvaluatePolynomial(coefficients, complexX);
		Console.WriteLine($"EvaluatePolynomial: {polynomialValue}");

		// Multiply polynomials
		var poly1 = new Complex[] { new Complex(1.0, 0.0), new Complex(2.0, 0.0) };
		var poly2 = new Complex[] { new Complex(3.0, 0.0), new Complex(4.0, 0.0) };
		var multipliedPoly = VMath.MultiplyPolynomials(poly1, poly2);
		Console.WriteLine($"MultiplyPolynomials: {string.Join(", ", multipliedPoly)}");

		// Divide polynomials
		var dividend = new Complex[] { new Complex(1.0, 0.0), new Complex(2.0, 0.0), new Complex(1.0, 0.0) };
		var divisor = new Complex[] { new Complex(1.0, 0.0), new Complex(1.0, 0.0) };
		var dividedPoly = VMath.DividePolynomial(dividend, divisor);
		Console.WriteLine($"DividePolynomial: quotient = {string.Join(", ", dividedPoly[0])}, remainder = {string.Join(", ", dividedPoly[1])}");

		// Compute the greatest common divisor
		int gcdValue = VMath.Gcd(48, 18);
		Console.WriteLine($"Gcd(48, 18) = {gcdValue}");

		// Compute the least common multiple
		int lcmValue = VMath.Lcm(4, 5);
		Console.WriteLine($"Lcm(4, 5) = {lcmValue}");

		// Compute the hypotenuse
		double hypotenuseValue = VMath.Hypotenuse(3.0, 4.0);
		Console.WriteLine($"Hypotenuse(3.0, 4.0) = {hypotenuseValue}");

		// Compute the modulus
		int modValue = VMath.Mod(10, 3);
		Console.WriteLine($"Mod(10, 3) = {modValue}");

		// Compute the factorial
		int factorialValue = VMath.Factorial(5);
		Console.WriteLine($"Factorial(5) = {factorialValue}");

		// Compute the square root
		decimal sqrtValue = VMath.Sqrt(16.0M);
		Console.WriteLine($"Sqrt(16.0) = {sqrtValue}");

		// Compute the unit in the last place (ULP)
		double ulpValue = VMath.Ulp(1.0);
		Console.WriteLine($"Ulp(1.0) = {ulpValue}");
	}
}

Pinned buffers (Vorcyc.Mathematics.Buffers)

0.9+ low-level pinned memory abstractions used by Signal (POHBuffer<float>) and other hot paths.

Type Description
IPinnedBuffer<T> Span<T>, unmanaged pointer, ref first element; IDisposable
POHBuffer<T> Pinned object heap buffer (used by Signal)
NativeBuffer<T> Unmanaged allocation via NativeMemory
PinnedArrayPool<T> Pool of reusable pinned buffers
PooledPinnedBuffer<T> RAII wrapper around pool rent/return
PinnableArrayExtension Helpers for PinnableArray<T>
IPinnedBufferExtensions / IPinnedBufferFactoryExtensions Copy/fill utilities
PinnableArrayOption Options for pinnable array creation

Types below are in namespace Vorcyc.Mathematics.Buffers. Constraint: T : unmanaged, INumberBase<T>.


Vorcyc.Mathematics.Buffers.IPinnedBuffer<T> interface

Common contract for fixed-address numeric buffers. Implementations: POHBuffer<T> (pinned managed array on the POH) and NativeBuffer<T> (NativeMemory).

Properties

Member Type Description
Span Span<T> Zero-copy view; invalid after Dispose or Reallocate
Memory Memory<T> Contiguous memory view
UnmanagedPointer T* Pointer to first element
ManagedPointer ref T Managed ref to first element
Length int Element count
IsDisposed bool Whether the buffer was disposed

Indexers

  • T this[int index] { get; set; }
  • Span<T> this[int startIndex, int length] { get; }
  • Span<T> this[Range range] { get; }

Methods

Method Description
Clear() Set all elements to default(T)
Fill(T value) Fill with a constant
Fill(T startValue, T step) Fill with arithmetic sequence startValue + step * i
FillWith<TOther>(TOther number) Fill via bitwise reinterpretation of another numeric type
Reallocate(int newLength) Resize; previously acquired spans/pointers are invalid
Dispose() Release resources

Vorcyc.Mathematics.Buffers.POHBuffer<T> class

Pinned object heap (POH) buffer allocated with GC.AllocateUninitializedArray<T>(length, pinned: true). Used internally by Signal (POHBuffer<float>). Implements IPinnedBuffer<T> and IDisposable. After Dispose, member access throws ObjectDisposedException.

Constructors

Constructor Description
POHBuffer(int length) Allocate length uninitialized elements (length > 0)
POHBuffer(T[] array) Copy from array
POHBuffer(T[] array, int offset, int count) Copy array segment
POHBuffer(ArraySegment<T> segment) Copy from segment
POHBuffer(ReadOnlySpan<T> span) Copy from span
POHBuffer(ReadOnlyMemory<T> memory) Copy from memory
POHBuffer(IEnumerable<T> collection) Copy from collection

Properties

Inherits Span, Memory, Length, UnmanagedPointer, ManagedPointer, IsDisposed from IPinnedBuffer<T>.

Indexers

Same as IPinnedBuffer<T> (this[int], this[int,int], this[Range]).

Methods

Method Description
Clear() / Fill(...) / FillWith<TOther>(...) Element-wise operations (see IPinnedBuffer<T>)
Reallocate(int newLength) Allocate new pinned array, copy min(old, new) elements
Dispose() Clear internal array reference
ToString() Debug string (first 50 elements + total count)

Implicit conversions

Conversion Description
T[] β†’ POHBuffer<T> Copy array into new buffer
POHBuffer<T> β†’ Span<T> buffer.Span
POHBuffer<T> β†’ T[] Underlying pinned array (must not be disposed)

Operator overloads

  • public static POHBuffer<T> operator +(POHBuffer<T> left, POHBuffer<T> right) β€” concatenate into a new buffer

Code example

using Vorcyc.Mathematics.Buffers;

using var buf = new POHBuffer<float>(1024);
buf.Fill(0f);
buf.Span[0] = 1f;

buf.Reallocate(2048);

Span<float> view = buf;          // implicit to Span<float>
float[] backing = buf;           // underlying T[] (while not disposed)

Vorcyc.Mathematics.Buffers.NativeBuffer<T> class

Unmanaged buffer allocated with NativeMemory.Alloc. Implements IPinnedBuffer<T>, MemoryManager<T>, and IDisposable. Suitable for native interop and scenarios that must avoid managed heap relocation. Has a finalizer; call Dispose() to free native memory promptly.

Constructors

Same overload set as POHBuffer<T>: (int length), (T[] array), (T[] array, int offset, int count), (ArraySegment<T>), (ReadOnlySpan<T>), (ReadOnlyMemory<T>), (IEnumerable<T>).

Properties

Same IPinnedBuffer<T> surface (Span, Memory, Length, UnmanagedPointer, ManagedPointer, IsDisposed).

Indexers

Same as IPinnedBuffer<T>.

Methods

Method Description
Clear() / Fill(...) / FillWith<TOther>(...) Element-wise operations
Reallocate(int newLength) NativeMemory.Realloc; invalidates prior spans/pointers
GetSpan() MemoryManager<T> span over native block
Pin(int elementIndex = 0) Returns MemoryHandle at offset (self-managed lifetime)
Unpin() No-op (native memory is always pinned)
Dispose() NativeMemory.Free; suppresses finalizer
ToString() Debug string (first 50 elements + total count)

Implicit conversions

Conversion Description
T[] β†’ NativeBuffer<T> Copy array into new native buffer
NativeBuffer<T> β†’ Span<T> buffer.Span

Operator overloads

  • public static NativeBuffer<T> operator +(NativeBuffer<T> left, NativeBuffer<T> right) β€” concatenate into a new buffer

Code example

using Vorcyc.Mathematics.Buffers;

using var native = new NativeBuffer<double>(4096);
native.Fill(0.0, 1.0);             // 0, 1, 2, ...

unsafe
{
    double* p = native.UnmanagedPointer;
    p[0] = 3.14;
}

native.Reallocate(8192);

POHBuffer vs NativeBuffer

POHBuffer<T> NativeBuffer<T>
Storage Pinned managed array (POH) NativeMemory unmanaged heap
GC pressure Array on POH Native allocation outside GC heap
Reallocate New pinned array + copy NativeMemory.Realloc
Typical use Signal samples, hot managed paths Interop, large off-heap blocks
Finalizer No Yes β€” always Dispose()

Related core types: PinnableArray<T>, Constants<T>, RandomNumberGenerator<T> (generic RNG alongside SimpleRNG_Fp32 / SimpleRNG_Fp64).

⚠️ **GitHub.com Fallback** ⚠️