user1281071
user1281071

Reputation: 895

Complex number in C

is it possible to do calculation like this in C?

A*exp(i*(b+c)) + D*exp(i*(e+f)),

where A,b,c,D,e,f are real numbers.

Upvotes: 1

Views: 2537

Answers (3)

pmg
pmg

Reputation: 108978

Section 7.3 in the C99 Standard (or C11 Standard) deals with complex numbers.

Example code

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

int main(void) {
    double A, b, c, D, e, f;
    complex double x;
    const complex double i = csqrt(-1);

    A = 1;
    b = 2;
    c = 3;
    D = 4;
    e = 5;
    f = 6;
    x = A * cexp(i * (b + c)) + D * cexp(i * (e + f));
    printf("value is %f + %fi\n", creal(x), cimag(x));
}

You can see the code running at ideone: http://ideone.com/d7xD7

The output is

value is 0.301365 + -4.958885i

Upvotes: 2

David Souther
David Souther

Reputation: 8174

In general, you cannot represent real numbers in C. There are an infinite number of real numbers, but C has only finite precision in its calculations. That said, ISOC99 has a data type to do operations on Complex numbers within those bounds. http://www.gnu.org/software/libc/manual/html_node/Complex-Numbers.html

The C99 complex numbers are fairly limited- it really only provides a way to multiply by i. CMATH provides some excellent extensions with much more functionality than C99. http://www.optivec.com/cmfuncs/

Upvotes: 1

High Performance Mark
High Performance Mark

Reputation: 78316

C99 introduces support for complex numbers. Whether or not your compiler implements this feature I don't know.

Upvotes: 3

Related Questions