Calculating Logarithm Base 2 in C/C
In C and C , there exists no built-in function specifically for calculating the logarithm base 2 (log2). While functions like log() for base e and log10() for base 10 are readily available, log2() is not directly provided.
Solution: Mathematical Transformation
To overcome this limitation, one can rely on a simple mathematical conversion. The formula to calculate log2 is as follows:
log2(x) = log(x) / log(2)
where:
Using Built-in Functions
Using the above formula, you can implement the log2() function using the built-in log() function:
C :
<code class="cpp">double log2(double x) { return log(x) / log(2); }</code>
C:
<code class="c">double log2(double x) { return log(x) / log(2.0); }</code>
Example Usage:
<code class="cpp">#include <iostream> #include <math.h> int main() { double x = 10; double log2_result = log2(x); std::cout << "log2(" << x << ") = " << log2_result << std::endl; return 0; }</code>
Output:
log2(10) = 3.321928
The above is the detailed content of How to Calculate Logarithm Base 2 (log2) in C/C ?. For more information, please follow other related articles on the PHP Chinese website!