Friday, August 10, 2012

compute euclidean norm for large vector

Input:
x = [x_1, x_2, ..., x_n]
when n is very large
compute ||x||_2

Solution:
||x||_2 = \sqrt(x[1]^2 + x[2]^2 + ... + x[n]^2)

One way to compute it is as following:
double m_sum = 0.0;
for (int i=1; i<=n;++i)
{
    m_sum  += x[i]^2;
}
return sqrt(m_sum);

However, it's possible that m_sum  overflow  overflow the MAX_FLOAT or MAX_DOUBLE on the computer (for large n). 
A safer algorithm would be:
 y=max(abs(x)) 
for (int i = 1; i<=n;i++){
      m_sum+=(x(i)/y)^2;
}
 return y*sqrt(m_sum); 

No comments:

Post a Comment