title: how i calculate cosine similarity by using jama
body: <p>could anyone help me with detecting the problem? I need to calculate the similarity between the query and a collection of documents, and I've been used the program : <a href="https://github.com/aliabbasrizvi/LatentSemanticIndexing][1]" rel="nofollow noreferrer">https://github.com/aliabbasrizvi/LatentSemanticIndexing][1]</a>. In this program, the similarity was calculated by "dot product" and I change it to "cosine similarity" but I got a high similarity score while I should get it between 0 and 1.
  can anyone tell me what is the wrong? is TF_IDF have any effect? or something else?</p>
  
  <p>those results that I got it"</p>
  
  <ol>
  <li><p>Document: b4, Relevance score: 2.185808108221954</p></li>
  <li><p>Document: h286, Relevance score: 1.1350011283882473E-16</p></li>
  </ol>
  
  <p>This is the code I was used it for similarity"</p>
  
  <pre><code>public double getVectorModulus(Matrix matrix) {                 
              double dotProduct = 0.0;
              double magnitude1 = 0.0;
              double magnitude2 = 0.0;
              double cosineSimilarity = 0.0;
              double a=0.0, b=0.0;
              int i = 0,j = 0;
                for ( i = 0; i &lt; matrix.getRowDimension(); i++)
                  { a=matrix.get(i, 0);
                    b= matrix.get(i, 0);
                     dotProduct += (a*b);  //a.b
                      magnitude1+=Math.pow(a, 2); //a^2
                      magnitude2+=Math.pow(b, 2); //b^2
                  }
              magnitude1+=Math.sqrt(magnitude1); //   sqrt(a^2)
              magnitude2+=Math.sqrt(magnitude2); //   sqrt(b^2)
              if(magnitude1 !=0.0 | magnitude2 !=0.0)
                  cosineSimilarity = dotProduct / (magnitude1 *magnitude2);    
      return cosineSimilarity;
      }
  </code></pre>