How can you use Ln function in C programing?
Asked Answered
W

4

6

Header file math.h is for mathematical functions like cos,sin, tan.. But how to write the ln function and not log?

Wein answered 10/12, 2015 at 15:3 Comment(8)
Why? Ln is just log base e.Carraway
log base e is log. What you're thinking of as log (log base 10) is log10 in the library.Notebook
You could use the taylor series or paulo's formulaSandler
Don't you mean log base e is Ln? Or am I confused?Carraway
no, I mean that the standard library function called log computes log base e.Notebook
OK, thanks. :) I'm more of a math/physics guy than a CS guy, so I didn't actually know that. :DCarraway
Thankyou guys. Very helpfulWein
The documentation is "helpful" too! ;-)Inviolate
D
33

The C function log is the natural logarithm, which mathematicians usually write as "ln".

The C function log10 is the logarithm base 10, which is sometimes written "log".

Did answered 10/12, 2015 at 15:7 Comment(0)
D
5

Remember math at school: logA_B = logA_C/logB_C

Dit answered 10/12, 2015 at 15:5 Comment(0)
C
2
double ln(double x) { return log(x); }

Or in a pinch

#define ln(x) log(x)
Coss answered 10/12, 2015 at 15:3 Comment(0)
S
-1
double ln(double x) {
    // ln(1 - y) = sum of -(y ^ k) / k from k = 1 to n but only if 0 < y < 1
    // taylor expansion formula of ln(x): https://furthermathematicst.blogspot.com/2011/06/71-taylor-polynomial-part-1.html
    int exponent = 0; // map the value x between 0 and 1
    while (x > 1.0) {x /= 2.0; exponent++;}
    while (x < 0.0) {x *= 2.0; exponent--;}
    int k, n = 1000; // iteration
    double y = 1 - x; // ln(1 - y) = ln(x) >> ln(y) = ln(1 - x)
    double initial_y = y;
    double result = 0;
    for (k = 1; k <= n; k++) { // sum of -(y ^ k) / k from k = 1 to n
        result += y / k;
        y *= initial_y; // y ^ k
    }
    return -1 * result + exponent * LN2;
}
Sweetmeat answered 1/10, 2024 at 12:48 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Bendite

© 2022 - 2025 — McMap. All rights reserved.