In C++, the log() function is defined in the <cmath> or <math.h> header file and is used to calculate the natural logarithm (base-e logarithm) of a given number. The natural logarithm uses Euler’s number e as the base, where the value of e is approximately 2.71828.
The log() function accepts integer, float, double, and long double values as input. It is widely used in mathematics, statistics, finance, scientific computing, and machine learning applications.
Suppose 'x' is a given number.
It has the following syntax.
x: It is the value whose natural logarithm is to be calculated.
Following are the return values of a given number.
| Parameter(x) | Return value |
|---|---|
| x>1 | Positive |
| x=1 | 0 |
| 1>x>0 | Negative |
| x=0 | -infinty |
| x<0 | Not a Number(nan) |
Here, we are going to discuss several examples to demonstrate the Math log() Function.
This example demonstrates how the log() function behaves when the input value is 1. Since log(1) is always 0, the function returns 0.
Output:
Value of x is : 1 Log value of x is : 0
Explanation:
In this example, the value of x is 1. Therefore, the function log() returns the positive value i.e 0.
This example demonstrates how to calculate the natural logarithm of a positive number greater than 1 using the log() function.
Output:
Value of x is : 3 Log value of x is : 1.09861
Explanation:
In this example, the value of x is 3. Therefore, the function log() returns the positive value i.e 1.09861
This example demonstrates how the log() function behaves when the input value is negative. In such cases, the function returns NaN (Not a Number).
Output:
Value of x is : -0.5 Log value of x is : nan
Explanation:
In this example, value of x is -0.5. Therefore, the function log() returns the Not a Number(nan).
This example demonstrates how the log() function behaves when the input value is 0. In this case, the function returns negative infinity.
Output:
clValue of x is : 0 Log value of x is : -inf
Explanation:
In this example, value of x is -1. Therefore, the function log() returns nan(Not a Number).
This example demonstrates how the log() function calculates the natural logarithm of a number whose value lies between 0 and 1.
Output:
Value of x is : 0.8 Log value of x is : -0.223144
Explanation:
In this example, value of x is 0.8. Therefore, the function log() returns the negative value i.e -0.22
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India