Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Which is more efficient? the formula or the function?

Asked by 8 years ago

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

0
I'm pretty sure magnitude is more efficient... You don't need to use so much math when you can simply say "magnitude" and it gives you the distance lightpower26 399 — 8y
0
xd, I am wondering that too xD, but the other is more close to maths so MATHS MATHS MATHS X-X buoyantair 123 — 8y
0
I would say the formula, not the function. User#11440 120 — 8y

2 answers

Log in to vote
1
Answered by
Scubadoo2 115
8 years ago

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

0
Cool. User#11440 120 — 8y
Ad
Log in to vote
0
Answered by 8 years ago

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!

0
I agree with your answer, but highly disagree with how you got to it. Just because something uses less code, does not mean it's more efficient. User#11440 120 — 8y
0
=3 buoyantair 123 — 8y
0
Wouldn't it be so that the less code a script executes the least amount of lag and it will go way smoother wouldn't that be what you mean by "efficient". Less lag and more smoothness = Efficiency. KingLoneCat 2642 — 8y

Answer this question