C++ Math log()

Last Updated : 16 May 2026

Math log() Function

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.

Mathematically:

Suppose 'x' is a given number.

Syntax

It has the following syntax.

Parameter

x: It is the value whose natural logarithm is to be calculated.

Return value

Following are the return values of a given number.

Parameter(x)Return value
x>1Positive
x=10
1>x>0Negative
x=0-infinty
x<0Not a Number(nan)

Examples of Math log() Function

Here, we are going to discuss several examples to demonstrate the Math log() Function.

Example 1: Calculate the Natural Logarithm of 1 Using log()

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.

Example 2: Calculate the Natural Logarithm of a Positive Number Greater Than 1

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

Example 3: Calculate the Natural Logarithm of a Negative Number

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).

Example 4: Calculate the Natural Logarithm of Zero Using log()

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).

Example 5: Calculate the Natural Logarithm of a Number Between 0 and 1

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