Search code examples
c#simdsystem.numerics

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


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?


Solution

  • 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.