4 ms·
What would you do differently with the norm function?
by tbabb 5y ago
What would you do differently with the norm function?
- hanche 5y agoTo compute a norm without overflow (unless it is totally unavoidable), let m be the maximum of the absolute values of the components. Divide each component by m, compute the square root of the sum of squares, and multiply by m. Only the last step might overflow, and if it does, it could not be avoided in any case. Incidentally, this normalization procedure also avoids underflow problems.
- tbabb 5y agoI see. I'd say it depends what the application is, then, because in graphics correctly handling (unlikely) extreme values would be quite secondary to performance, especially for an inner loop function like norm. See fastinvsqrt, e.g., which is extremely imprecise!
- hanche 5y agoIn many applications there is definitely no reason to worry about overflow when computing norms. That is more of an issue if you are writing library code for general use, which should be as robust as you can make it.
- FabHK 5y agoAbsolutely, I should’ve been more precise: it’s perfectly fine for most applications, but not for a library, or, say, manned aviation. So, yeah, when optimising for accuracy, range, or speed you might implement it differently, respectively. I mean, papers have been written about sqrt(a^2+b^2) alone… :-) https://arxiv.org/abs/1904.09481 https://arxiv.org/abs/1904.09481
- xscott 5y agoThe hypot() function avoids many overflow and underflow cases: return hypot(hypot(q.w, q.x), hypot(q.y, q.z));
- tbabb 5y agoInterestingly, with clang and -O3 I get identical assembly for hypot() and the "naive" implementation.