How do you implement complex numbers into programming?

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 5K views
epkid08
Messages
264
Reaction score
1
For instance, if I had a function of a complex variable z, how can I evaluate that function using a program?
 
Physics news on Phys.org
The complex number "5 + 4i" can be represented using 2 variables,

float real_part = 5, imag_part = 4;

of course it's easier if you put them into a class, C++ has the standard std::complex class.

Then you just define arithmetic operators on the class using operator overloading.
 
Fortan supports complex numbers, so it's not an issue. C++ supports complex numbers via the class complex <complex.h>, and the associated overloaded operators and math functions. For a language like C, you'd need to create a set of fuctions to do this.
 
Jeff Reid said:
C++ supports complex numbers via the class complex <complex.h>

In standard C++, the header file is <complex>, i.e. simply use

#include <complex>

This allows you to use the usual arithmetic operations on complex numbers, as well as providing various functions specific to complex numbers. For example:

Code:
#include <iostream>
#include <complex>

using namespace std;

int main ()
{
    complex<double> z1, z2, z3;
    z1 = complex<double> (1.0, 2.0);
    z2 = complex<double> (3.0, 4.0);
    cout << "z1 = " << z1 << endl;
    cout << "z2 = " << z2 << endl;
    z3 = z1 + z2;
    cout << "Sum = " << z3 << endl;
    z3 = z1 * z2;
    cout << "Product = " << z3 << endl;
    return 0;
}

which produces the output

Code:
z1 = (1,2)
z2 = (3,4)
Sum = (4,6)
Product = (-5,10)
 
Last edited: