Implementation of `.Magnitude`?

How was the .Magnitude property actually implemented under the hood? How is it different than the Z axis?

I can recreate it quite simply as

print((workspace.Part1.Position - workspace.Part2.Position).Magnitude)
-- 31.894357681274414
print(math.abs((workspace.Part1.Position - workspace.Part2.Position).Z))
-- 31

with the only difference being the .Magnitude property is a float whereas the Z axis is an integer.

Well the Z axis is an integer due to the math.abs

I don’t know how .Magnitude is implemented under the hood, but the way you described it working is more of a coincidence that the values are close than that being accurate.

If you think about the Pythagorean Theorem, it’s a^2 + b^2 = c^2. In 2D Vectors, c would be the magnitude.

It’s the same idea with 3D vectors. It’s x^2 + y^2 + z^2 = c^2, where c is the magnitude.

This pattern applies to any number of dimensions (4D and beyond.)

2 Likes

You can use math.round for rounding numbers, and math.abs to make the sign of the number always positive.

I am not sure if I still understand the difference between simply taking the Z axis

math.abs also rounds the number, however from my past experiences it only rounds down

Magnitude is just the distance from the origin point (0, 0, 0). So the Z axis plays a part of the calculation of the magnitude, but it is not the magnitude.

For instance, if you had a Vector3 value of (20, 0, 0), the Z axis is 0, but the Magnitude is 20, which so happens to map directly to the X axis since no other axes have a value.

A Vector3 of (20, 30, 10) will have a magnitude of about 37.4, which is calculated as:

= sqrt( 20^2 + 30^2 + 10^2 )
= sqrt( 400 + 900 + 100 )
= sqrt ( 1400 )
= 37.41657

And as you can see, the result has no direct equality with the Z axis.


If your confusion is about what the Z axis represents: The Z axis typically represents the depth in 3D space (at least on Roblox). To visualize this, look down at your mouse. Move it left and right. You’re moving it on the X axis. Now move it forward and back. That moves it on the Z axis. Now lift it up and put it down. You’re moving it on the Y axis.

10 Likes