Skip to content

Instantly share code, notes, and snippets.

@leegao
Created April 5, 2011 04:15
Show Gist options
  • Save leegao/903021 to your computer and use it in GitHub Desktop.
Save leegao/903021 to your computer and use it in GitHub Desktop.
Fast matrix pow function in lua (O(1) running time, for whatever n)
function m_pow(matrix, n)
local a1 = -(matrix[1][1]+matrix[2][2])
local a2 = (matrix[1][1]*matrix[2][2]-matrix[1][2]*matrix[2][1]) -- determinant
-- r^2 + a1*r + a2 = 0, find rs -> (1/2)*(-a1 +- sqrt(a1^2 - 4*a2))
local rt = math.sqrt(a1^2-4*a2)
local r1 = (-a1+rt)/2
local r2 = (-a1-rt)/2
local r1n = r1^n
local r2n = r2^n
local b2 = (r2n-r1n)/(r2-r1)
local b1 = (r2*r1n - r1*r2n)/(r2-r1)
return {{b2*matrix[1][1]+b1, b2*matrix[1][2]}, {b2*matrix[2][1], b2*matrix[2][2]+b1}}
end
function print_matrix(matrix)
print(unpack(matrix[1]))
print(unpack(matrix[2]))
end
matrix = {{1,2},
{3,4}}
print_matrix(m_pow(matrix, 400))
@FloooD
Copy link

FloooD commented Apr 5, 2011

take out the negative sign from a1 to make it even faster xdddddddddd

btw r2-r1 = -rt

@FloooD
Copy link

FloooD commented Apr 5, 2011

oh and if rt is 0 then ull divide by zero lol

@leegao
Copy link
Author

leegao commented Apr 5, 2011

yeah, 0 gives me indeterminant for the identity matrix, or anytime when a+d = 2sqrt(ad-bc), rare cases though so I'm not gonna lose sleep :P

@FloooD
Copy link

FloooD commented Apr 5, 2011

uh... if rt=0 then do it the normal way with a for loop or something?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment