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

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

Linda Hamilton
Release: 2024-10-27 21:28:01
Original
695 people have browsed it

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)
Copy after login

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>
Copy after login

C:

<code class="c">double log2(double x) {
    return log(x) / log(2.0);
}</code>
Copy after login

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>
Copy after login

Output:

log2(10) = 3.321928
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template