Skip to content

Skymath

Taiizor edited this page Mar 1, 2023 · 21 revisions

Skymath Class - Skylark.Helper Namespace

The Skymath class provides useful math functions.

Methods

Clamp Method

The Clamp method clamps a value between a minimum and a maximum value.

Syntax

public static T Clamp<T>(T Value, T Min, T Max) where T : IComparable<T>

Parameters

Parameter Description
Value The value to clamp.
Min The minimum value to compare.
Max The maximum value to compare.

Type Parameters

Type Parameter Description
T The comparable type to clamp.

Return Value

The clamped value.

Examples

using Skylark.Helper;

int value = 10; int min = 0; int max = 5; int clampedValue = Skymath.Clamp<int>(value, min, max); // Output: 5

Average Method

The Average method finds the average of all elements given. It is implemented entirely by the user to be compatible between any types.

Syntax

public static TOut Average<TIn, TSum, TOut>(IEnumerable<TIn> Elements, TSum Zero, Func<TSum, TIn, TSum> AddToSum, Func<TSum, int, TOut> DivSum)

Parameters

Parameter Description
Elements The elements to average.
Zero The zero as TSum for the sum start.
AddToSum A function to add the TSum with the next TIn element.
DivSum A function to divide the TSum with 2. The output is returned.

Type Parameters

Type Parameter Description
TIn The type of the input elements.
TSum The type of the summing variable.
TOut The type of the output average.

Return Value

The average of all elements as type TOut.

Examples

using Skylark.Helper;
// Find the average of integers.
int[] numbers = {1, 2, 3, 4};
int averageInt = Skymath.Average<int, int, int>(numbers, 0, (sum, next) => sum + next, (sum, count) => sum / count); // Output: 2
// Find the average of floats.
float[] floatNumbers = {1.1f, 2.2f, 3.3f, 4.4f};
float averageFloat = Skymath.Average<float, float, int>(floatNumbers, 0.0f, (sum, next) => sum + next, (sum, count) => sum / count); // Output: 2.75

In the example code above, the Skymath.Average method is used to find the average of a sequence of numbers. The first argument to the method is an array of numbers, and the second argument is the initial value of the sum. The third argument is a lambda expression that takes two arguments, the sum so far and the next number in the sequence, and returns the new sum. The fourth argument is another lambda expression that takes the final sum and the count of numbers in the sequence, and returns the average. The method is generic, so it can be used with any numeric type, and any type for the sum and count. The example shows how it can be used with both int and float arrays.

Clone this wiki locally