pythonnumpymathcomplex-numberspython-cmath

Inserting complex functions in a python code


I have been trying to insert $e^ix$ as matrix element. The main aim is to find the eigenvalue of a matrix which has many complex functions as elements. Can anyone help me how to insert it? My failed attempt is below:

for i in range(0,size):
                    
            H[i,i]=-2*(cmath.exp((i+1)*aj))
            H[i,i+1]=1.0
            H[i,i-1]=1.0

'a' is defined earlier in the program. The error flagged shows that aj is not defined. Using cmath I thought a complex number can be expontiated as (x+yj). Unfortunately, I couldn't figure out the right way to use it. Any help would be appreciated


Solution

  • Define a small float array:

    In [214]: H = np.eye(3)
    In [215]: H
    Out[215]: 
    array([[1., 0., 0.],
           [0., 1., 0.],
           [0., 0., 1.]])
    

    Create a complex number:

    In [216]: 1+3j
    Out[216]: (1+3j)
    In [217]: np.exp(1+3j)
    Out[217]: (-2.6910786138197937+0.383603953541131j)
    

    Trying to assign it to H:

    In [218]: H[1,1]=np.exp(1+3j)
    <ipython-input-218-6c0b228d2833>:1: ComplexWarning: Casting complex values to real discards the imaginary part
      H[1,1]=np.exp(1+3j)
    In [219]: H
    Out[219]: 
    array([[ 1.        ,  0.        ,  0.        ],
           [ 0.        , -2.69107861,  0.        ],
           [ 0.        ,  0.        ,  1.        ]])
    

    Now make an complex dtype array:

    In [221]: H = np.eye(3).astype( complex)
    In [222]: H[1,1]=np.exp(1+3j)
    In [223]: H
    Out[223]: 
    array([[ 1.        +0.j        ,  0.        +0.j        ,
             0.        +0.j        ],
           [ 0.        +0.j        , -2.69107861+0.38360395j,
             0.        +0.j        ],
           [ 0.        +0.j        ,  0.        +0.j        ,
             1.        +0.j        ]])
    

    edit

    For an array of values:

    In [225]: a = np.array([1,2,3])
    In [226]: np.exp(a+1j*a)
    Out[226]: 
    array([  1.46869394+2.28735529j,  -3.07493232+6.7188497j ,
           -19.88453084+2.83447113j])
    
    In [228]: H[:,0]=np.exp(a+1j*a)
    In [229]: H
    Out[229]: 
    array([[  1.46869394+2.28735529j,   0.        +0.j        ,
              0.        +0.j        ],
           [ -3.07493232+6.7188497j ,  -2.69107861+0.38360395j,
              0.        +0.j        ],
           [-19.88453084+2.83447113j,   0.        +0.j        ,
              1.        +0.j        ]])