/// <summary> /// A Vector extension method that determines the mean of the given parameters. /// </summary> /// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception> /// <param name="source">The source to act on.</param> /// <returns>The mean value.</returns> public static double Mean(this Vector source) { if (source.Length == 0) { throw new InvalidOperationException("Cannot compute average of an empty vector."); } return(source.Sum() / source.Length); }
/// <summary>Computes.</summary> /// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception> /// <param name="x">The Vector to process.</param> /// <param name="y">The Vector to process.</param> /// <returns>A double.</returns> public double Compute(Vector x, Vector y) { if (x.Length != y.Length) throw new InvalidOperationException("Cannot compute similarity between two unequally sized Vectors!"); var xSum = x.Sum(); var ySum = y.Sum(); var xElem = (x^2).Sum() - ((xSum * xSum) / x.Length); var yElem = (y^2).Sum() - ((ySum * ySum) / y.Length); return (x.Dot(y) - ((xSum * ySum) / x.Length)) / System.Math.Sqrt(xElem * yElem); }
/// <summary> /// Normalizes the values so that the sum of all values is 1. /// <para>Values should be positive prior to normalization for correctness.</para> /// </summary> /// <param name="v">Vector to normalize.</param> /// <returns>Vector.</returns> public static Vector Normalize(this Vector v) { double sum = v.Sum(); if (sum == 0) { throw new InvalidOperationException("Cannot normalize a zero sequence."); } Vector v_t = v.Each(d => d / sum, true); return(v_t); }
/// <summary>An IEnumerable<Vector> extension method that sums the given source.</summary> /// <param name="v">The v to act on.</param> /// <returns>A Vector.</returns> public static double Sum(this Vector v) { return(Vector.Sum(v)); }