Selected Reading

C++ cmath sqrt()Function



The C++ cmath sqrt() is used to compute the square root of a given number. It takes a non-negative number as input and returns its square root. It supports different floating-point types, like float, double, and long double, allowing for flexibility in precision depending on the needs of the computation.

This function is widely used in mathematical computations, such as calculating distances in geometry, solving equations, and in various scientific applications, including statistics and data analysis.

Syntax

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

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

Parameters

  • x- The value, whose square root is computed. If the argument is negative, a domain error occurs.

Return Value

The function returns the square root of the given number as a floating-point value.

Time Complexity

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

Example 1

The following example shows the basic usage of the sqrt() function by calculating the square root of a given number.

#include <iostream>
#include <cmath>
int main() {
   double num = 25.0;
   std::cout << "Square root of 25 is: " << std::sqrt(num) << std::endl;
   return 0;
}

Output

Output of the above code is as follows

Square root of 25 is: 5

Example 2

In this example, the input is a float value, and std::sqrt() computes its square root. This demonstrates that std::sqrt() operates with float data types.

#include <iostream>
#include <cmath>
int main() {
   float num = 16.0f;
   std::cout << "Square root of 16 is: " << std::sqrt(num) << std::endl;
   return 0;
}

Output

Following is the output of the above code

Square root of 16 is: 4

Example 3

The following example shows the ability of the sqrt() function to manage and accurately compute the square root of very small numbers.

#include <iostream>
#include <cmath>
int main() {
   double value = 1e-10; // 0.0000000001
   double result = sqrt(value);
   std::cout << "The square root of " << value << " is " << result << std::endl;
   return 0;
}

Output

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

The square root of 1e-10 is 1e-05
cpp_cmath.htm
Advertisements