What is the log2() function in D?
The log2() function in D uses the base 2 to calculate the logarithm of a number.
Figure 1 shows the mathematical representation of the log2() function.
Note: We need to import
std.mathin our code, in order to use thelog2()function. We can import it like this:import std.math
Syntax
log2(number)
// number should be float, double or real.
Parameter
This function requires a
Return value
The log2() function uses the base 2 to return the logarithm of a number.
Note:
- If the parameter value is
positive infinity, then thelog2()function returnspositive infinity.- If the parameter value is
NaNornegative infinity, then thelog2()function returnsNaN.- If the parameter value is -
NaN, then thelog2()function returns-NaN.- If the parameter value is <=
0, then thelog2()function returnsnegative infinity.
Code example
The code written below shows us how to use the log2() function in D:
import core.stdc.stdio;import std.stdio;//header required for functionimport std.math;int main(){//integerwriteln ("The value of log2(2) : ",log2(2));//positive double valuewriteln ("The value of log2(2.56) : ",log2(2.56));//ewriteln ("The value of log2(E) : ",log2(E));//exceptional outputswriteln ("The value of log2(-0.0) : ",log2(-0.0));writeln ("The value of log2(0.0) : ",log2(0.0));writeln ("The value of log2(real.infinity) : ",log2(real.infinity));writeln ("The value of log2(-real.infinity) : ",log2(-real.infinity));writeln ("The value of log2(real.nan) : ",log2(real.nan));writeln ("The value of log2(-real.nan) : ",log2(-real.nan));return 0;}
Code explanation
-
Line 4: We add the header
std.math, which is required for thelog2()function. -
Line 9: We calculate the log base 2 of an integer value, using the
log2()function. -
Line 12: We calculate the log base 2 of a positive double value, using the
log2()function. -
Line 15: We calculate the log base 2 of
e, using thelog2()function. -
Lines 18–26: We calculate the log base 2 of
exceptional numbers, using thelog2()function.