Raddy
Raddy

Reputation: 39

Efficient Magnitude Calculation of 3D Vector

I'm working on an inertial measurement project using a 3-axis accelerometer and an Arduino. I want the Arduino to take in the x, y, and z g-values and spit out the magnitude. Since the |a| = sqrt(x^2 + y^2 + z^2) is computationally expensive, I wanted to investigate whether there was an alternative algorithm that could be used to speed it up (I'm willing to sacrifice a little accuracy).

I read about the Alpha-max, Beta-min method, but that appears to only work for 2D vectors. Is there anything similar for 3D vectors?

EDIT: Program language is C++

Upvotes: 3

Views: 3958

Answers (3)

Eph
Eph

Reputation: 267

There is also std::hypot, which computes the length of a 2D vector (since C++11) or 3D vector (since C++17). For in-between versions of C++, you can compute the length of a 3D vector using the 2D version of the function as std::hypot(std::hypot(x, y), z).

Hypot is more robust against over- and underflow (especially during squaring of the individual components) compared to computing the formula manually. It might or might not be faster, depending on your standard library and hardware.

Upvotes: 0

August van Casteren
August van Casteren

Reputation: 1

Normalizing Spatial Vectors without Square Root If you use what this guy posted to calculate the unit vector, you can then divide the x of the original vector by the calculated unit vector's x.

Upvotes: 0

MattH
MattH

Reputation: 131

If you have a fast way of calculating two-dimensional magnitude, then perhaps the three-dimensional magnitude can be restructured in those terms.

The three-dimensional magnitude can be derived from the Pythagorean theorem.

|a| = sqrt(sqrt(x^2 + y^2)^2 + z^2) = sqrt(x^2 + y^2 + z^2)

Upvotes: 2

Related Questions