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

后端 未结 10 1084
灰色年华
灰色年华 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条回答
  •  闹比i
    闹比i (楼主)
    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!

提交回复
热议问题