What is the sqrt() function in D?
The sqrt() function in D returns the square root of a non-negative number.
The figure below shows the mathematical representation of the sqrt() function:
Note: We need to import
std.mathin our code to use thesqrt()function. We can import it with the following:import std.math
Syntax
sqrt(number)
// The number should be floating, double, or real.
Parameter
sqrt() requires a non-negative number as a parameter.
Return value
sqrt() returns the square root of the number sent as a parameter.
Note:
- If
-0.0,real.infinity,real.nan, or-real.nanis sent as a parameter, the function returns the parameter as it is.- If
-real.infinityornumber < 0.0is sent as a parameter, the function returns-nan.
Working example
The code below shows the use of the sqrt() function in D.
import core.stdc.stdio;import std.stdio;//Header required for the functionimport std.math;int main(){//Perfect square rootwriteln ("The value of sqrt(4.0) : ",sqrt(4.0));writeln ("The value of sqrt(0.0) : ",sqrt(0.0));writeln ("The value of sqrt(25.0) : ",sqrt(25.0));//Non-perfect square rootwriteln ("The value of sqrt(4.4) : ",sqrt(4.4));//Exceptional outputswriteln ("The value of sqrt(-0.0) : ",sqrt(-0.0));writeln ("The value of sqrt(real.infinity) : ",sqrt(real.infinity));writeln ("The value of sqrt(-real.infinity) : ",sqrt(-real.infinity));writeln ("The value of sqrt(real.nan) : ",sqrt(real.nan));writeln ("The value of sqrt(-real.nan) : ",sqrt(-real.nan));writeln ("The value of sqrt(-4.5) : ",sqrt(-4.5));return 0;}
Explanation
-
Line 4: We add the
std.mathheader required for thesqrt()function. -
Lines 9 to 13: We calculate the square root value of the perfect square numbers
4,0, and25usingsqrt(). -
Line 16: We calculate the square root value of a non-perfect square number
4.4usingsqrt(). -
Lines 19 to 24: We calculate the square root value of exceptional numbers using
sqrt().