Sum of elements in System.Numerics.Vector<T> in .NET 4.6

3.5k views Asked by At

I cannot figure out a way how to get a sum of elements in a vector of System.Numerics.Vector type.

double sum(System.Numerics.Vector<double> vect)
{
     // Something like 
     // double sum = 0;
     // foreach e in vect { sum += e; } 
     // return sum;

     // Vector.method???
     // For loop ???
}

If it's actually possible? How can I do this?

3

There are 3 answers

12
saucecontrol On BEST ANSWER

Assuming you did intend to have a Vector that could contain (in today's hardware) either 2 or 4 doubles, this will sum them.

double vectorSum = Vector.Dot(yourDoubleVector, Vector<double>.One);

The Dot method calculates the dot product of the two vectors, which is defined for two vectors A and B of size n as A1 * B1 + A2 * B2 + ... + An * Bn

So the dot product of a vector A and another vector of all 1's would be just the sum of the items in vector A.

2
Marc Gravell On

From .NET 6 onward, this is exposed directly via Vector.Sum<T>(Vector<T> value):

double sum(System.Numerics.Vector<double> vect) // note can be 'static'
    => Vector.Sum(vect);
0
zyl910 On

If you don't want to upgrade to .NET 6.0, you can use the VectorTraits library. This library supports .NET Framework 4.5+ programs.

This library provides the Vectors.Sum method.