C++ Valarray::sin() Function



The sin value of each element in the valarray is determined using the sin() function of the valarray class. This method calculates the sine value and returns a new valarray with the calculated sine value as its result.

Sine is a trigonometric function that mathematically describes the angle of a right-angled triangle. The ratio of the hypotenuses to the opposite side's length gives its value. This function overloads cmath's sin() function, one for each element.

Syntax

Following is the syntax for C++ Valarray::sin() Function −

sin (const valarray<T>& x);

Parameters

x − It contains elements of a type for which the unary function sin is defined.

Examples

Example 1

Let's look into the following example, where we are going to use sin() function and retrieving the output.

#include <iostream>
#include <valarray>
using namespace std;

int main() {
   valarray<double>
   varr = { 1,0.23,3,0.45,5 };
   valarray<double> valarray1;
   valarray1 = sin(varr);
   cout << "The New sin"
      << " Valarray is : "
      << endl;
   for (double& x : valarray1) {
      cout << x << " ";
   }
   cout << endl;
   return 0;
}

Output

when we compile and run the above program, this will produce the following result −

The New sin Valarray is : 
0.841471 0.227978 0.14112 0.434966 -0.958924

Example 2

Considering the following example, where we are going to use sin() function and retrieving output of both original valarray and sin valarray.

#include <iostream>
#include <valarray>
using namespace std;

int main() {
   valarray<double> myvalarray = {0.23,-3,-0.6,1.23,4.5 };
   cout << "The Original Valarray is : ";
   
   for (double& ele : myvalarray)
      cout << ele << " ";
   valarray<double> sinValarray;
   sinValarray = sin(myvalarray);
   cout << "\nThe sin Valarray is : ";
   
   for (double& ele : sinValarray)
      cout << ele << " ";
   return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

The Original Valarray is : 0.23 -3 -0.6 1.23 4.5 
The sin Valarray is : 0.227978 -0.14112 -0.564642 0.942489 -0.97753  

Example 3

In the following example, we are going to use sin() function with integral type and retrieving the output.

#include <iostream>
#include <cmath>
using namespace std;

int main() {
   int a = 3;
   double result;
   result = sin(a);
   cout << "sin(a) = " << result << endl;
   return 0;
}

Output

On running the above program, it will generate the output as shown below −

sin(a) = 0.14112
Advertisements