Complex Number Math

Got a LiveCode personal license? Are you a beginner, hobbyist or educator that's new to LiveCode? This forum is the place to go for help getting started. Welcome!

Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller

Post Reply
rcrist
Posts: 1
Joined: Sat Nov 19, 2011 7:07 pm

Complex Number Math

Post by rcrist » Sun Dec 04, 2011 9:43 pm

Here is a complex number math library using a 2-element array as the real and imaginary part of the number. Anyone have another way to handle complex math?

Code: Select all

function Complex x,y
   local CResult
   
   put x into CResult[1]
   put y into CResult[2]
   return CResult
end Complex

function CAdd a,b
   local CResult
   
   put a[1] + b[1] into CResult[1]
   put a[2] + b[2] into CResult[2]
   return CResult
end CAdd

function CSub a,b
   local CResult
   
   put a[1] - b[1] into CResult[1]
   put a[2] - b[2] into CResult[2]
   return CResult
end CSub

function CMul a,b
   local CResult
   
   put a[1]*b[1]-a[2]*b[2] into CResult[1]
   put a[1]*b[2]+a[2]*b[1] into CResult[2]
   return CResult
end CMul

function CConj b
   local CResult
   
   put b[1] into CResult[1]
   put -b[2] into CResult[2]
   return CResult
end CConj

function CDiv a,b
   local CNum, bConj, CResult, rDen
   
   put CConj(b) into bConj
   put CMul(a,bConj) into CNum
   put b[1]^2+b[2]^2 into rDen
   put Cnum[1]/rDen into CResult[1]
   put Cnum[2]/rDen into CResult[2]
   return CResult
end CDiv

function CMag a
   local CResult
   put sqrt(a[1]^2+a[2]^2) into CResult
   return CResult
end CMag

function CAng a
   local CResult
   put atan2(a[2],a[1])*180/pi into CResult
   return CResult
end CAng

function PrintMagAng a
   local CResult
   put "Mag = " & CMag(a) & "  < = " & CAng(a) into CResult
   return CResult
end PrintMagAng

function CMtxMul a,b,order
   local CNum, CResult
   
   repeat with i =1 to order
      repeat with j=1 to order
         repeat with k=1 to order
            put CMul(a[i,k],b[k,j]) into CNum
            put CAdd(CResult[i,j],CNum) into CResult[i,j]
         end repeat 
      end repeat
   end repeat
   return CResult
end CMtxMul

function PrintComplex a
   local CResult
   put a[1] & "+j" & a[2] into CResult
   return CResult
end PrintComplex

function PrintCArray a
   local CResult
   put 2 into order
   
   Put "" into CResult
   repeat with i =1 to order
      repeat with j=1 to order
         put Cresult & PrintComplex(a[i,j]) & "   " into Cresult
      end repeat
      put Cresult & return into Cresult
   end repeat
   return CResult
end PrintCArray


Post Reply