简体   繁体   中英

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

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?

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

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM