![]() |
VOOZH | about |
There are various functions available in the C++ Library to calculate the square root of a number. Most prominently, sqrt is used that is defined in <cmath> header file. It takes double as an argument. The <cmath> header defines two more inbuilt functions for calculating the square root of a number (apart from sqrt) which has an argument of type float and long double.
Following are the functions used for calculating square root in C++ :
The above functions have been discussed in detail below:
The sqrt() function returns the square root of a number of type double.
double sqrt(double arg);
15.000000000000 17.320508075689
1. It is mandatory to give the argument otherwise, it will give an error no matching function for call to 'sqrt()' as shown below.
Output
prog.cpp:9:19: error: no matching function for call to ‘sqrt()’
answer = sqrt();2. If we pass a negative value in the argument domain error occurs and the output will be the Square root of -a, which is -nan.
Square root of -2 is -nan
The sqrtf() function returns the square root of a number of type float.
float sqrtf(float arg)
15.000000000000 17.320508956909
The sqrtl() function returns the square root of a number of type long double with more precision.
long double sqrtl(long double arg)
1000000000.000000000000 999999999.999999999476
When working with integers of the order 1018, calculating its square root with sqrt function may give an incorrect answer due to precision errors as default functions in programming language work with floats/doubles. But sqrtl function will always give an accurate answer.
Following is an illustration given below shows the exact difference when working with long integers with sqrt and sqrtl.
1) Using sqrt function
1000000000.000000000000 1000000000.000000000000
2) Using sqrtl function
1000000000.000000000000 999999999.999999999476