qrakhens-toolkit-dotnet/Qrakhen.Alqebra/Class1.cs

43 lines
1.1 KiB
C#

using System.Numerics;
namespace Qrakhen.Alqebra;
public interface IVector<T>
{
int Dimensions { get; }
T this[int index] { get; }
double Magnitude { get; }
}
public readonly record struct Vector<T>(params T[] Values) :
IVector<T>
where T : INumber<T>
{
public int Dimensions => Values.Length;
public T this[int index] => Values[index];
public double Magnitude => Math.Sqrt(Values.Select(n => n * n).Sum(n => (dynamic)n));
}
public static class VectorExtensions
{
/// <summary>
/// Slower add that works with vectors of any dimension.
/// </summary>
public static Vector<T> Add<T>(this Vector<T> self, Vector<T> other) where T : INumber<T>
{
ArgumentOutOfRangeException.ThrowIfNotEqual(self.Dimensions, other.Dimensions);
T[] values = new T[self.Dimensions];
for (int i = 0; i < self.Dimensions; i++)
{
values[i] = self[i] + other[i];
}
return new Vector<T>(values);
// i think this v is just too slow
return new Vector<T>(self.Values.Zip(other.Values).Select(tuple => tuple.First + tuple.Second).ToArray());
}
}