log() in C: Natural Logarithm

log() returns the natural logarithm of a positive value, using base e. Its argument must be greater than zero for an ordinary real-valued result.

Syntax Top ↑

double log(double x);

Natural Logarithm Top ↑

#include <math.h>
#include <stdio.h>

int main(void) {
    double value = 10.0;

    printf("log(10) = %.6f\n", log(value));
    return 0;
}

Recover an Exponent Top ↑

#include <math.h>
#include <stdio.h>

int main(void) {
    double e_squared = exp(2.0);

    printf("%.2f\n", log(e_squared));
    return 0;
}
For real-number calculations, pass a value greater than zero. Use log10() when the required base is 10.

Preserved Logarithm Variations Top ↑

Logarithm with Any Valid Base

#include <math.h>
#include <stdio.h>

double log_base(double value, double base) {
    return log(value) / log(base);
}

int main(void) {
    double value = 8.0;
    double base = 2.0;

    if (value <= 0.0 || base <= 0.0 || base == 1.0) {
        printf("Invalid logarithm input.\n");
        return 1;
    }

    printf("log base %.0f of %.0f = %.2f\n",
           base, value, log_base(value, base));

    return 0;
}

Handle the log() Domain Before Calling It

#include <math.h>
#include <stdio.h>

int main(void) {
    double values[] = {1000.0, 0.0, -5.0};
    size_t count = sizeof values / sizeof values[0];

    for (size_t i = 0; i < count; i++) {
        if (values[i] <= 0.0) {
            printf("log(%.1f) is outside the real-number domain.\n",
                   values[i]);
        } else {
            printf("log(%.1f) = %.6f\n",
                   values[i], log(values[i]));
        }
    }

    return 0;
}




plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer