-1

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
nad
  • 2,640
  • 11
  • 55
  • 96
  • 5
    You should be using `cexp()` in the C version, no? – kindall Jan 05 '17 at 07:17
  • 1
    What's `exp`? Are you using C++, or `tgmath.h`? The `exp` function in C normally doesn't take complex numbers. And how are you examining the result, anyway? Show us runnable code. – user2357112 Jan 05 '17 at 07:19
  • I think numpy and c will both produce the same answer once you switch `exp` to `cexp`. The right answer is -1i. That's what numpy is really saying when you assume that 6e-17 is really zero. – bruceg Jan 05 '17 at 07:30

2 Answers2

2

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
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
0

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));
bruceg
  • 2,433
  • 1
  • 22
  • 29