Home  >  Article  >  Backend Development  >  How to Calculate Logarithm Base 2 (log2) in C/C ?

How to Calculate Logarithm Base 2 (log2) in C/C ?

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 21:28:01604browse

How to Calculate Logarithm Base 2 (log2) in C/C  ?

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:

  • log(x) is the natural logarithm (base e)
  • log(2) is the constant value of approximately 0.693

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn