numjs icon indicating copy to clipboard operation
numjs copied to clipboard

Complex number arithmetic

Open mklilley opened this issue 4 years ago • 0 comments

Hi.

Thanks so much for creating this library @nicolaspanel. I'm currently using it to make an ObservableHQ notebook to solve the Schrödinger equation using Fourier transforms.

As part of the solution I need to multiply arrays of complex numbers that come out of using the FFT as described in your documentation. I could not see a method to perform the required multiplication so I created a function myself which you can see below.

function cmultiply(z1,z2) {
   
 // z3 = z1*z2 = (x1+iy1)*(x2+iy2) = (x1*x2 - y1*y2) + i(y1*x2 + x1*y2)
  
  let x1 = z1.slice(null,[0,1]) // real part of z1
  let y1 = z1.slice(null,1)     // imag part of z1
  
  let x2 = z2.slice(null,[0,1]) // real part of z2
  let y2 = z2.slice(null,1)     // imag part of z2
  
 let x3 = nj.subtract(nj.multiply(x1,x2), nj.multiply(y1,y2)) // real part (x1*x2 - y1*y2)
 let y3 = nj.add(nj.multiply(y1,x2), nj.multiply(x1,y2))      // imag part (y1*x2 + x1*y2)
  
 return  nj.concatenate([x3,y3])
  
}

I'm sure this isn't the most efficient way to do this. I was wondering whether you have any advice on how it could be done better?

Thanks for your time and thanks again for making numjs

mklilley avatar Oct 25 '20 16:10 mklilley