tags:

views:

159

answers:

6
typedef struct Complex{
double real;
int img;
} Complex;

I've seen people use it as a type like:

Complex sqrt( double x) {
}

how do 'real' and 'img' play a role in this type of function? Thanks

+3  A: 

You might use it like this:

Complex sqrt( double x) {
    Complex r;
    r.real = f(x);
    r.img = g(x);
    return r;
}

In this example, f(x) and g(x) would be calls to functions that compute the real and imaginary part of the square root of the complex number x. (In reality you would probably calculate the square root inside the sqrt() function, but I'm just showing this as an example of how to use the Complex structure.)

Here is a reference that explains structures in C, which might be helpful for you.

Greg Hewgill
A: 

Complex numbers have a wide range of uses in mathematics - what the role is will depend on the context of the application.

FinnNk
A: 

I imagine that if the signature is

Complex sqrt( double x);

Then x represents a real value. So Complex.img could be a 0/1 representing whether x was positive or negative.

Example (taking x as a real number)

//C like pseudocode
Complex sqrt(double x){
      Complex result={0,0};
      if (x==0) return result;

      if (x<0){
          result.img =1;
          real = abs(x);
      }  
      result.real= sqrt_(x);//calculates square root of a positive value.
      return result;

}

    //some other place
   double r =-4.0;

   Complex root = sqrt(r);

   //prints "Square root of -4.0 is 2i"
   printf("Square root of %.2f is %.2f%c",r,root.real,(root.img?'i':''));
Tom
+4  A: 

It can be used like this:

Complex sqrt(double x) {
    Complex c = {0.0, 0.0};
    if ( x>= 0.0 )
       c.real = square_root(x);
    else
       c.img = square_root(-x);
    return c;
}

I don't know if it's a mistake, but the Complex::img should be also a double.

(note that Complex numbers is a superset of Reals, so a complex number can be used in the place of a double if its imaginary part is zero)

Nick D
A: 

The imaginary part should a be double too.

For a real (double x):

Sqrt(x).Real = x >= 0 : Math::Sqrt(x) : 0;
Sqrt(x).Imaginary = x < 0 : Math::Sqrt(x) : 0;

Like FinnNk suggested, read a little about complex mathematics.

Danny Varod
A: 

The square root of a complex number is a calculation not typically found on your hand calculator....

Check out DeMoivre’s Theorem which is used to change variables to polar coordinates - for which there is a closed form formula for the square-root of a complex number, a + ib.

Paul

Paul