Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C library function - log()

C library function - log()

C Standard Library - <math.h> C Standard Library -

Description

C Library Function double log(double x) Return x the natural logarithm (logarithm with base e).

log() is a function in the C standard library a function in the C standard library used to compute the natural logarithm (base e) of a floating-point number. This is a commonly used mathematical function, widely applied in scientific computing, finance, and engineering.

Declaration

Here is the declaration of the log() function.



#include 



double log(double x);

float logf(float x);

long double logl(long double x);

Parameters

Return Value

Error handling

Example

The following example demonstrates the use of the log() function.

Example

#include

#include

int

main

(

)

{

   

double

x

,

ret

;

   x

=

2.7

;

   

/* Compute log(2.7) */

   ret

=

log

(

x

)

;

   

printf

(

"log(%lf) = %lf"

,

x

,

ret

)

;

   

   

return

(

0

)

;

}

Let's compile and run the above program, which will produce the following result:



log(2.700000) = 0.993252

Handling logarithms of multiple values

The following example shows how to handle logarithms of multiple values:

Example

#include

#include

#include

int

main

(

)

{

   

double

values

[

]

=

{

1.0

,

2.718281828

,

10.0

,

1.0

,

0.0

}

;

   

int

num_values

=

sizeof

(

values

)

/

sizeof

(

values

[

0

]

)

;

   

for

(

int

i

=

0

;

i

<

num_values

;

i

++

)

{

       

double

x

=

values

[

i

]

;

        errno

=

0

;

 

// Reset errno

       

double

result

=

log

(

x

)

;

       

if

(

errno

==

EDOM

)

{

           

printf

(

"Domain error: log(%f) is not defined\n"

,

x

)

;

       

}

else

if

(

errno

==

ERANGE

)

{

           

printf

(

"Range error: log(%f) results in an overflow or underflow\n"

,

x

)

;

       

}

else

{

           

printf

(

"log(%f) = %f\n"

,

x

,

result

)

;

       

}

   

}

   

return

0

;

}

Code Analysis

Let's compile and run the above program, which will produce the following result:

log(1.000000) = 0.000000

log(2.718282) = 1.000000

log(10.000000) = 2.302585

log(-1.000000) = nan

log(0.000000) = -inf

Use Cases

log() The function has a wide range of uses in many applications, including but not limited to:

Summary

log() The function is used to compute the natural logarithm of a floating-point number and is an important tool for handling logarithmic operations. By making proper use of log(), logarithmic operations can be performed in scientific computing, finance, and engineering applications, with possible error conditions handled properly.

C Standard Library - <math.h> C Standard Library -