Selected Reading

C++ cmath acos() Function



The C++ cmath acos() function calculates the arccosine (or inverse cosine) of a number. It takes a cosine value as input, You can only use numbers between -1 and 1 as input, anything outside this range is invalid and doesn't produce a result. This function is helpful in fields like trigonometry, geometry, and physics for calculating angles based on cosine values.

Syntax

Following is the syntax for C++ cmath acos() function.

double acos(double x);
or
float acos(float x);
or
long double acos(long double x);

Parameters

  • x - The value ( must be in the range [-1, 1] ) for which to calculate the arccosine.

Return Value

The function returns the angle in radians as a floating-point value within the range [0, ].

Time Complexity

The time complexity of this function is constant, i.e.,O(1).

Example 1

In the following example we are going to calculate the arccosine of a value.

#include <iostream>
#include <cmath>
int main() {
   double value = 0.5;
   std::cout << "Arccosine of 0.5: " << std::acos(value) << " radians" << std::endl;
   return 0;
}

Output

Output of the above code is as follows

Arccosine of 0.5: 1.0472 radians

Example 2

Let's calculate the angle in degrees by converting the result of std::acos from radians to degrees. Note: To convert the result from radians to degrees, use the formula Degrees = Radians 180/

#include <iostream>
#include <cmath>
int main() {
   double value = -0.5;
   double angle_radians = std::acos(value);
   double angle_degrees = angle_radians * (180.0 / M_PI);
   std::cout << "Arccosine of -0.5: " << angle_degrees << " degrees" << std::endl;
   return 0;
}

Output

Following is the output of the above code

Arccosine of -0.5: 120 degrees

Example 3

In the following example, we are going to calculate and print the arccosine values for a set of cosine values within the range [-1, 1] in increments of 0.5.

#include <iostream>
#include <cmath>
int main() {
   for (double value = -1.0; value <= 1.0; value += 0.5) {
      std::cout << "Arccosine of " << value << ": " << std::acos(value) << " radians" << std::endl;
   }
   return 0;
}

Output

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

Arccosine of -1: 3.14159 radians
Arccosine of -0.5: 2.0944 radians
Arccosine of 0: 1.5708 radians
Arccosine of 0.5: 1.0472 radians
Arccosine of 1: 0 radians
cpp_cmath.htm
Advertisements