how to calculate the Euclidean norm of a vector in R?

后端 未结 10 1077
灰色年华
灰色年华 2021-02-01 13:22

I tried norm, but I think it gives the wrong result. (the norm of c(1, 2, 3) is sqrt(1*1+2*2+3*3), but it returns 6..

相关标签:
10条回答
  • 2021-02-01 13:57
    norm(c(1,1), type="2")     # 1.414214
    norm(c(1, 1, 1), type="2")  # 1.732051
    
    0 讨论(0)
  • 2021-02-01 13:58

    I'mma throw this out there too as an equivalent R expression

    norm_vec(x) <- function(x){sqrt(crossprod(x))}
    

    Don't confuse R's crossprod with a similarly named vector/cross product. That naming is known to cause confusion especially for those with a physics/mechanics background.

    0 讨论(0)
  • 2021-02-01 14:02

    If you have a data.frame or a data.table 'DT', and want to compute the Euclidian norm (norm 2) across each row, the apply function can be used.

    apply(X = DT, MARGIN = 1, FUN = norm, '2')
    

    Example:

    >DT 
    
            accx       accy       accz
     1: 9.576807 -0.1629486 -0.2587167
     2: 9.576807 -0.1722938 -0.2681506
     3: 9.576807 -0.1634264 -0.2681506
     4: 9.576807 -0.1545590 -0.2681506
     5: 9.576807 -0.1621254 -0.2681506
     6: 9.576807 -0.1723825 -0.2682434
     7: 9.576807 -0.1723825 -0.2728810
     8: 9.576807 -0.1723825 -0.2775187
    
    > apply(X = DT, MARGIN = 1, FUN = norm, '2')
     [1] 9.581687 9.582109 9.581954 9.581807 9.581932 9.582114 9.582245 9.582378
    
    0 讨论(0)
  • 2021-02-01 14:02

    Following AbdealiJK's answer,

    I experimented further to gain some insight.

    Here's one.

    x = c(-8e+299, -6e+299, 5e+299, -8e+298, -5e+299)
    sqrt(sum(x^2))
    norm(x, type='2')
    

    The first result is Inf and the second one is 1.227355e+300 which is quite correct as I show you in the code below.

    library(Rmpfr)
    y <- mpfr(x, 120)
    sqrt(sum(y*y))    
    

    The result is 1227354879.... I didn't count the number of trailing numbers but it looks all right. I know there another way around this OVERFLOW problem which is first applying log function to all numbers and summing up, which I do not have time to implement!

    0 讨论(0)
  • 2021-02-01 14:04

    This is a trivial function to write yourself:

    norm_vec <- function(x) sqrt(sum(x^2))
    
    0 讨论(0)
  • 2021-02-01 14:04

    We can also find the norm as :

    Result<-sum(abs(x)^2)^(1/2)
    

    OR Even You can also try as:

    Result<-sqrt(t(x)%*%x)
    

    Both will give the same answer

    0 讨论(0)
提交回复
热议问题