Hi,
So I have a small question about the usage of .Magnitude
and a Custom function, as while playing around with both, I noticed a bit of a Difference between the two.
If you dont know, getting the Distance of something from both 2D, and 3D spaces, you use the Pythagorean Thorem.
Usually the Pythagorean Thorem a² + b² = c² when using it for 2D spaces, but for 3D Spaces the equation is a² + b² + c² = d², after that you get the spare root of that number, and that would be your Distance.
I Decided to make my own function, which is this:
local function distance (p0, p1) -- custom function
return sqrt((p0.X - p1.X)^2 + (p0.Y - p1.Y)^2 + (p0.Z - p1.Z)^2)
end
Or if you wanted to simplify it:
local function distance (p0, p1) -- also custom function
local p = p0 - p1 -- subtracts p0 and p1 before pythagroean theroem
return sqrt(p.X^2 + p.Y^2 + p.Z^2)
end
Which testing, it works as normal, but this is .Magnitude
, which is normally used to get the Distance of a Vector3
.
(p0 - p1).Magnitude -- Magnitude function
When testing, they work about the same, giving the exact same amount, but not really, the custom function compared to .Magnitude
is usually off by .0001 or less which I also checked by printing them together, this is an example from some of the tests I did:
-- This came from printing the Data.
Is the same? false -- a print that returned a boolean (d1 == d2)
Point 0: (80, 80, 47) -- starting Position
Point 1: (78, 47, 27) -- end Position
Magnitude: 38.63935852050781
CustomFunc: 38.63935817272331 -- Custom Function is off by a small amount
When testing this code, I have it randomly set to a different amount everytime, which looks like this:
-- This is done before both of the codes fire
local p0 = Vector3.new(random(1, 100), random(1, 100), random(1, 100))
local p1 = Vector3.new(random(1, 200), random(1, 1200), random(1, 200))
Why does this happen? and which is more Accurate to use?