- Home /
How to get a vector magnitude without calculating the square root?
I can´t use sqrmagnitude since I really need the exact distance. I thought using Vector3.distance, but the scripting reference says that is the same as a magnitude. All of this is for a SweepTest that is going to be thrown along a vector. I need to see if it will collide with anything, and using sqrmagnitude will give a wrong collision if it happens after the max length of the vector.
Answer by Bunny83 · Dec 14, 2019 at 09:53 PM
You simply can't. That's impossible since the length of a vector is defined by the Euclidean distance and if you need the exact distance you need to calculate the square root. However why do you actually care about the square root? On modern hardware the FPU sqrt instruction is probably faster than anything you might come up with in managed .NET code. So I'm not sure why you care about the square root. If you want to normalize a vector and pair it with a sweep test, I'm pretty sure the sweep test will be the more expensive operation involved.
There are some native bit magic implementations like Fast InvSqrt, but they just calculate an approximation. Also you probably only get good performance if compiled in native code. Implementing it in C# would probably not make much sense. See this SO question and the comments below the top anser. People have implemented the fast inverse square root algorithm in C# and it was even slower than the native 1f/Math.Sqrt(x)
.
How often do you actually want to use it per frame? If it's not at least 10000 times it's most likely not worth to even think about that. Don't get me wrong. It's totally fine to use the square distance instead of the distance if the algorithm allows this replacement. However in many cases this is not possible. Any unjustified premature micro-optimisations usually does more harm than any good.