Just a quick heads-up for anyone who reads this - to calculate a square root (or any other root, for that matter), use Lua math equations, not math.sqrt.
According to the test I made, using the equivalent x ^ 0.5 is approximately four times faster than localized math.sqrt. I knocked up a simple test for it, and here’s my result:
Using localized math.sqrt:
[lua]
Test Finished:
50000000 calculations
3.718415 secs taken
74.3672 ms on average
Test Finished:
50000000 calculations
3.713201 secs taken
74.26284 ms on average
Test Finished:
50000000 calculations
3.723258 secs taken
74.46406 ms on average
[/lua]
Using 100 ^ 0.5:
[lua]
Test Finished:
50000000 calculations
0.971279 secs taken
19.42424 ms on average
Test Finished:
50000000 calculations
0.973754 secs taken
19.47412 ms on average
Test Finished:
50000000 calculations
0.940703 secs taken
18.81362 ms on average
[/lua]
Here’s my test (comment/uncomment the lines to use different methods):
[lua]
local print = print
local math_sqrt = math.sqrt
local system_getTimer = system.getTimer
local function test(iterations)
local time = 0
local totalTime = 0
local testStart = system_getTimer()
for i = 1, iterations do
local startTime = system_getTimer()
for i = 1, 1000000 do
--local t = 100 ^ 0.5
local t = math_sqrt(100)
end
local testTime = system_getTimer() - startTime
time = time + testTime
end
time = time / iterations – Average the result
totalTime = system_getTimer() - testStart
local result = “\n\nTest Finished: \n\t” … iterations * 1000000 … " calculations\n\t" … totalTime / 1000 … " secs taken\n\t" … time … " ms on average"
print(result)
end
for i = 1, 3 do
test(50)
end
[/lua]
There’s the root speed part of the title. Now, for the “handy root function” part - you can calculate the nth root of any number with this quick function:
[lua]
local function nroot(n, r) return n ^ (1 / r) end
local result1 = nroot(50, 3) – The cube root of 50
local result2 = nroot(128.5, 9) – The ninth root of 128.5
[/lua]
Anyhow… Just testing out some root calculations
- Caleb