How can I avoid overflow/underflow when computing the euclidean norm of a vector?

Viewed 534

I was trying to use log and then take the exp, but that makes only sense if I deal with products or divisions. One would usually define

Euclidean_Norm <- function(x) sqrt(sum(x^2))

But I can't handle overflow/underflow. I was thinking to implement

Euklidean_Norm2 <- function(x) log(exp(sqrt(sum(x^2))))

If I take for example

c(34212432, 21343210940, 5412359103) 

I get Inf with Euklidean_Norm2 and the Euklidean_Norm does not work. But it should be representable in R, since

sqrt(34212432^2 + 21343210940^2 + 5412359103^2)
[1] 22018797760

I am looking for a way to avoid this kind of overflows. I would be grateful for any hint.

0 Answers
Related