Quote: "@chafari - If you're testing lots of distances then don't use the sqrt() "
Quote: "I haven't checked the whole code but why take square roots at all if you only need to find the closest?"
You are both right !!, It was just an example I tested, but actually I use vector. Something like:
null = make vector3(1)
set vector3 1, x1# - x2#, y1# - y2#, z1# - z2#
dist# = length vector3(1)
Edited.
I'm not quite sure which method is fastest. Time ago I found this comparison code.
rem Create objects
randomize timer()
backdrop off
null = make vector3(1)
global dist# as float
global Loops as integer = 100000
make object cube 1, 10
make object cube 2, 10
Restart:
position object 1, rnd(10000)-5000 , rnd(10000)-5000 , rnd(10000)-5000
position object 2, rnd(10000)-5000 , rnd(10000)-5000 , rnd(10000)-5000
x1# = object position x(1): x2# = object position x(2)
y1# = object position y(1): y2# = object position y(2)
z1# = object position z(1): z2# = object position z(2)
cls
rem Calculate Classic SQRT
t = timer()
for x = 1 to Loops
dist# = sqrt(((x1# - x2#)^2) + ((y1# - y2#)^2) + ((z1# - z2#)^2))
next x
t1 = timer()-t
print "Time needed for Classic SQRT Calculation: ", t1, " ms"
print "Dist# = ", dist#
print " "
rem Calculate SQRT ^2
t = timer()
for x = 1 to Loops
x# = x1# - x2#
y# = y1# - y2#
z# = z1# - z2#
dist# = sqrt(x#^2+y#^2+z#^2)
next x
t2 = timer()-t
print "Time needed for x#^2 Calculation: ", t2, " ms"
print "Dist# = ", dist#
print " "
rem Calculate SQRT x# * x#
t = timer()
for x = 1 to Loops
x# = x1# - x2#
y# = y1# - y2#
z# = z1# - z2#
dist# = sqrt(x#*x# + y#*y# + z#*z#)
next x
t3 = timer()-t
print "Time needed for x# * x# Calculation: ", t3, " ms"
print "Dist# = ", dist#
print " "
rem Calculate SQRT ^0.5
t = timer()
for x = 1 to Loops
x# = x1# - x2#
y# = y1# - y2#
z# = z1# - z2#
dist# = (x#*x# + y#*y# + z#*z#)^0.5
next x
t4 = timer()-t
print "Time needed for ^0.5 distance: ", t4, " ms"
print "Dist# = ", (dist#)
print " "
rem Calculate Vector
t = timer()
for x = 1 to Loops
set vector3 1, x1# - x2#, y1# - y2#, z1# - z2#
dist# = length vector3(1)
next x
t6 = timer()-t
print "Time needed for Sasuke's Vector-Calculation: ", t6, " ms"
print "Dist# = ", dist#
print " "
rem Calculate Heuristic - DO NOT USE
t = timer()
for x = 1 to Loops
dist# = Abs(x1# - x2#) + Abs(y1# - y2#) + Abs(z1# - z2#)
next x
t5 = timer()-t
print "Time needed for Heuristic-Calculation: ", t5, " ms"
print "Dist# = ", dist#, " -- Inaccurate -- DO NOT USE"
print " "
print "Press any key to run it again, or ESC to exit."
sync
while not escapekey()
nice wait 200
if spacekey() then goto Restart
endwhile
Cheers.
I'm not a grumpy grandpa
