Why does NumPy.exp show a different result than exp in C

518 views Asked by At

I am converting some Python code to C code.

Below Python NumPy exp on complex number outputs (6.12323399574e-17-1j) for k=1, l=4.

numpy.exp(-2.0*1j*np.pi*k/l)

I convert it to C code like below. But the output is 1.000000.

#include <complex.h>
#define PI 3.1415926535897932384626434
exp(-2.0*I*PI*k/l)

What am I missing?

2

There are 2 answers

0
bruceg On

Here's the right C code to print out your answer:

    x = cexp(-2.0*I*PI*0.25);
    printf("%f + i%f\n", creal(x), cimag(x));
0
eyllanesc On

You must use cimag and creal to print the data.

C version:

#include <stdio.h>
#include <complex.h>
#include <tgmath.h>


int main(){
    int k=1;
    int l=4;
    double PI = acos(-1);
    double complex z = exp(-2.0*I*PI*k/l);
    printf(" %.1f%+.1fj\n", creal(z), cimag(z));
    return 0;
}

Output:

0.0-1.0j

Python Version:

import numpy as np

k=1
l=4
z = np.exp(-2.0*1j*np.pi*k/l)
print(z)

Output:

6.12323399574e-17-1j