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.

Mathematical representation of the "log2()" function

Note: We need to import std.math in our code, in order to use the log2() 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 numberThis number must be greater than 0. for which the logarithm is to be calculated.

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 the log2() function returns positive infinity.
  • If the parameter value is NaN or negative infinity, then the log2() function returns NaN.
  • If the parameter value is -NaN, then the log2() function returns -NaN.
  • If the parameter value is <= 0, then the log2() function returns negative 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 function
import std.math;
int main()
{
//integer
writeln ("The value of log2(2) : ",log2(2));
//positive double value
writeln ("The value of log2(2.56) : ",log2(2.56));
//e
writeln ("The value of log2(E) : ",log2(E));
//exceptional outputs
writeln ("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 the log2() 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 the log2() function.

  • Lines 18–26: We calculate the log base 2 of exceptional numbers, using the log2() function.

Free Resources