Euler identifier in C

Today I was messing with complex numbers in C and so (naturally) I was trying to program in Euler's identity. We all know that e iĻ€ = -1, but somehow C wants to return a (positive) 1 - why? Thank!

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

double main(void){
    double complex exponent = M_PI*I;
    double complex power = exp(exponent);
    printf("%.f\n",power);
    return power;
}

      

+3


source to share


1 answer


A complex number is forced back to real because it exp

expects an argument double

. The collision discards the imaginary part and only skips the real part, which is equal to 0

. Consequently, exp(0) = 1

.

You should use cexp

instead exp

. cexp

expects a double complex

.

You also shouldn't cast complex

directly to printf

, but should explicitly print the real and imaginary parts like this:



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

double main(void){
    double complex exponent = M_PI*I;
    double complex power = cexp(exponent);
    printf("%.f + %.fi\n", creal(power), cimag(power));
    return power;
}

      

Also, returning double

from is main

just weird ...

+6


source







All Articles