Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

How do you implement complex numbers into programming?

  1. Jul 12, 2009 #1
    For instance, if I had a function of a complex variable z, how can I evaluate that function using a program?
     
  2. jcsd
  3. Jul 12, 2009 #2
    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.
     
  4. Jul 12, 2009 #3

    rcgldr

    User Avatar
    Homework Helper

    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.
     
  5. Jul 13, 2009 #4

    jtbell

    User Avatar

    Staff: Mentor

    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 (Text):

    #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 (Text):

    z1 = (1,2)
    z2 = (3,4)
    Sum = (4,6)
    Product = (-5,10)
     
     
    Last edited: Jul 13, 2009
  6. Jul 16, 2009 #5

    daniel_i_l

    User Avatar
    Gold Member

Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: How do you implement complex numbers into programming?
  1. Program Implementation (Replies: 21)

  2. How do programs work? (Replies: 5)

Loading...