C++ cmath sqrt , sqrtf and sqrtl function

The C++ <cmath> sqrt,sqrtf and sqrtl function compute the square root of the value.The declaration of the functions are given below.

1 float sqrt(float x);
2 double sqrt(double x);
3 long double sqrt(long double x);
4 float sqrtf(float x);
5 long double sqrtl(long double x);

x -The value whose square root is to be calculated.

Return type
floating point -The square root of x.

Some points to note:

i) sqrt(x) is same as √x.

ii) A domain error occur if x<0.

iii) If NAN is passed ‘nan’ is returned.

iv) If +∞ is passed +∞ is retunred,if -∞ is passed ‘nan’ is returned.

Code example

/*Passing floating point value*/
cout&l;t< “sqrt(4)=” << sqrt(4) << endl;

/*Passing -ve value*/
cout&l;t< “sqrt(-5)=” << sqrt(-5) << endl;

/*Passing NAN*/
cout&l;t< “sqrt(NAN)=” << sqrt(NAN) << endl;

/*Passing -INFINTIY*/
cout&l;t< “sqrt(-INFINITY)=” << sqrt(-INFINITY) << endl;


sqrt(4)= 2
sqrt(-5)= nan
sqrt(NAN)= nan
sqrt(-INFINITY)= nan

sqrtf and sqrtl


i)The 4th version sqrtf is same as the 1st version float sqrt(float).The ‘f‘ character appended to ‘sqrtf’ stands for ‘float’ which signify the argument and return type of the function.

ii)The 5th version sqrtl is same as the 3rd version long double sqrt(long double).The ‘l‘ character in ‘sqrtl’ stands for ‘long double’ which signify the argument and return type of the function.

Code example

#include <typeinfo>

/*sqrtf */
cout<< “*sqrtf\n”;
float f=2;
cout<< typeid( sqrtf(2) ).name() << endl /*identify type of sqrtf retunred value */
<< typeid( sqrt(f) ).name() << endl; /*identify type of sqrt(float) returned value */

cout<< “*sqrtl\n”;
long double ld=2;
cout<< typeid( sqrtl(2) ).name() << endl /*indentify type of sqrtl returned value */
<< typeid( sqrt(ld) ).name() << endl; /*identify type of sqrt(long double) returned value*/


e (means ‘long double’)
e (means ‘long double’)

*Side Note

sqrt(x) is much faster than the equivalent function pow(x , 0.5).

Link: C++ cmath pow function