Пример #1
0
        /// <summary>
        /// Returns the inner product of this vector with the specified vector.
        /// </summary>
        /// <param name="that">that the other vector</param>
        /// <returns>the dot product between this vector and that vector</returns>
        /// <exception cref="ArgumentException">if the lengths of the two vectors are not equal</exception>
        public double Dot(SparseVector that)
        {
            if (_dims != that._dims) throw new ArgumentException("Vector lengths disagree");
            var sum = 0.0;

            // iterate over the vector with the fewest nonzeros
            if (_st.Size() <= that._st.Size())
            {
                foreach (int i in _st.Keys())
                    if (that._st.Contains(i)) sum += Get(i) * that.Get(i);
            }
            else
            {
                foreach (int i in that._st.Keys())
                    if (_st.Contains(i)) sum += Get(i) * that.Get(i);
            }
            return sum;
        }
Пример #2
0
        public void Run()
        {
            var a = new SparseVector(10);
            var b = new SparseVector(10);

            a.Put(3, 0.50);
            a.Put(9, 0.75);
            a.Put(6, 0.11);
            a.Put(6, 0.00);
            b.Put(3, 0.60);
            b.Put(4, 0.90);
            Console.WriteLine("a = " + a);
            Console.WriteLine("b = " + b);
            Console.WriteLine("a dot b = " + a.Dot(b));
            Console.WriteLine("a + b   = " + a.Plus(b));

            Console.ReadLine();
        }
Пример #3
0
 /// <summary>
 /// Returns the scalar-vector product of this vector with the specified scalar.
 /// </summary>
 /// <param name="alpha">alpha the scalar</param>
 /// <returns>the scalar-vector product of this vector with the specified scalar</returns>
 public SparseVector Scale(double alpha)
 {
     SparseVector c = new SparseVector(_dims);
     foreach (int i in _st.Keys()) c.Put(i, alpha * Get(i));
     return c;
 }
Пример #4
0
 /// <summary>
 /// Returns the sum of this vector and the specified vector.
 /// </summary>
 /// <param name="that">that the vector to add to this vector</param>
 /// <returns>the sum of this vector and that vector</returns>
 /// <exception cref="ArgumentException">if the dimensions of the two vectors are not equal</exception>
 public SparseVector Plus(SparseVector that)
 {
     if (_dims != that._dims) throw new ArgumentException("Vector lengths disagree");
     var c = new SparseVector(_dims);
     foreach (int i in _st.Keys()) c.Put(i, Get(i));                // c = this
     foreach (int i in that._st.Keys()) c.Put(i, that.Get(i) + c.Get(i));     // c = c + that
     return c;
 }