Ok,
I am trying to make a math library for myself to experiment stuff
so, I came up with a case where you want to find the distance btw 2 points.
Now everyone normally uses this
(p1 - p2).magnitude
Well, I am not great at maths and stuff, so I refer my academic textbooks (ugh)
and here's how I made a distance function
function module.Distance(p1, p2) return math.sqrt((p1.X - p2.X)^2 + (p1.Y - p2.Y)^2 + (p1.Z - p2.Z)^2) end
I am wondering which is the best to use.....
=3
I just tested it, magnitude is better. I tested it by measuring how long it took to do it multiple times using tick()
. This is the code I used:
wait(2) print("Starting") p1 = Vector3.new(34,54,76) p2 = Vector3.new(13,1,98) times = 1000000 it = tick() for i=1, times do this = math.sqrt((p1.X - p2.X)^2 + (p1.Y - p2.Y)^2 + (p1.Z - p2.Z)^2) end result1 = tick() - it it = tick() for i=1, times do this = (p1-p2).magnitude end result2 = tick() - it if result1 < result2 then -- Math time is less than magnitude time print("Math is better") elseif result2 < result1 then -- Magnitude time is less than math time print("Magnitude is better") else print("They are both the same") end print("Result 1 = " .. result1) print("Result 2 = " .. result2)
Try it out if you want, it should say Magnitude is better
for whatever you use for p1
and p2
I believe that the formula is more efficient because the less code you can use to get something done the better and also the easier it will be to review your code. So I believe that the magnitude
formula would be best to use for what you are trying to achieve.
I hope I helped and thank you for reading this answer!