Cos() function for complex number in C++


Given the task is to show the working of cos() function for complex numbers in C++.

The cos() function is a part of the C++ standard template library. It is a little different from the standard cos() function. Instead of calculating the cosine of simple integral or rational numbers, it calculates the complex cosine values of complex numbers.

The mathematical formula for calculating complex cosine is

cos(z) = (e^(iz) + e^(-iz))/2

where “z” represents the complex number and “i” represents iota.

The complex number should be declared as follows

complex<double> name(a,b)

Here, <double> that is attached to the “complex” data type describes an object that stores ordered pair of objects, both of type “double’. Here the two objects represent the real part and the imaginary part of the complex number that we want to enter.

<complex> header file should be included to call the function for complex numbers.

Syntax

The syntax is as follows −

cos(complexnumber)

Example

Input: complexnumber(3,4)
Output: -27.0349,-3.85115

Explanation − The following example shows how we can use the cos() function for calculating the cosine values of a complex number.

Here 3 is the real part and 4 is the imaginary part of the complex number as shown in the input, and then we get the cosine values in the output as we pass the complex number into the cos() function.

Approach used in the below program as follows −

  • First declare a complex number, let us say complexnumber(a,b) and then assign it a complex value.
  • Two values should be assigned to the variable complexnumber(a,b). The first value will be the real part of the complex number and the second value will be the imaginary part of the complex number.
  • Let’s say complexnumber(2,3), so this will represent the complex number 2+3i.
  • Now pass the complexnumber(2,3) we created into the cos() function

Example

 Live Demo

#include<iostream>
#include<complex>
using namespace std;
int main() {
   complex<double> complexnumber(2,3);
   cout<<cos(complexnumber);
   return 0;
}

Output

If we run the above code it will generate the following output −

<-1.56563,-3.29789>

Here 2 is the real part and 3 is the imaginary part of the complex number, as we pass our complex number into the cos() function, we get the cosine values in the output as shown.

Updated on: 20-Jan-2020

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements