Example: Calculate Roots

The following example shows how you can use the complex Mathematics Library to calculate the roots of a complex number. For every positive integer n, each complex number z has exactly n distinct nth roots. Suppose that in the complex plane the angle between the real axis and point z is theta, and the distance between the origin and the point z is r. Then z has the polar form (r, theta), and the n roots of z have the values:

sigma
sigma x omega
sigma x omega^2
sigma x omega^3
.
.
.
sigma x omega^(n - 1)

where omega is a complex number with the value:

omega = (cos(2pi / n), sin(2pi / n))

and sigma is a complex number with the value:

sigma = r^(1/n) (cos(theta / n), sin(theta / n))

The following code includes two functions, get_omega() and get_sigma(), to calculate the values of omega and sigma. The user is prompted for the complex value z and the value of n. After the values of omega and sigma have been calculated, the n roots of z are calculated and printed.

   // Calculating the roots of a complex number

   #include <iostream.h>
   #include <complex.h>
   #include <math.h>
   // Function to calculate the value of omega for a given value of n
   complex get_omega(double n) 
   {
      complex omega = complex(cos((2.0*M_PI)/n), sin((2.0*M_PI)/n));
      return omega;
   } 
   // function to calculate the value of sigma for a given value of
   // n and a given complex value

   complex get_sigma(complex comp_val, double n)
   {
      double rn, r, theta;
      complex sigma;
      r = abs(comp_val);
      theta = arg(comp_val);
      rn = pow(r,(1.0/n));
      sigma = rn * complex(cos(theta/n),sin(theta/n));
      return sigma;
   }
   int main(int argc, char *argv[])
   {
      double n;
      complex input, omega, sigma;
      //
      // prompt the user for a complex number
      //
      cout << “Please enter a complex number: ”;
      cin >> input;
      //
      // prompt the user for the value of n
      //
      cout << “What root would you like of this number? ”;
      cin >> n;
      //
      // calculate the value of omega
      //
      omega = get_omega(n);
      cout << “Here is omega ” << omega << endl;
      //
      // calculate the value of sigma
      //
      sigma = get_sigma(input,n);
      cout << “Here is sigma ” << sigma << '\n'
           << “Here are the ” << n << “ roots of ” << input << endl;
      for (int i = 0; i < n ; i++)
   {
         cout << sigma*(pow(omega,i)) << endl;
   }
   return 0
} 

This example produces the output shown below in regular type, given the input shown in bold:

   Please enter a complex number: (-7, 24)
   What root would you like of this number? 2
   Here is omega ( -1, 1.22465e-16)
   Here is sigma ( 3, 4)
   Here are the 2 roots of ( -7, 24)
   ( 3, 4)
   ( -3, -4)

Related Concepts

Related Tasks