log() in C
Overview
log() in C programming language, declared in the math.h header file, is a function that returns the natural logarithm of a passed parameter.
Introduction
In C programming, we use the log() function to compute the natural logarithm of a number. The log() function is present in math.h library file, which contains many different mathematical functions. We need to include the <math.h> header file to use the log in C.
Syntax of log in C
Here you can see the log() function takes an argument x of type double and returns the floating-point value.
log() function with float or long double datatype can be used as follows -
Parameters of log in C
log() take one variable as a parameter and compute the natural logarithm value of that variable. We can pass the different types of parameters/values to the log function in C.
We can pass decimal values like float, double, long double, etc., or we can pass the integer values.
Return Values of log in C
The log() function will return the natural logarithm of x ( i.e., the log value of x with base e), and the type of this return value is double.
Exceptions of log in C
There are two types of runtime errors that can occur due to passing the parameters of a specific range. These exceptions are handled by the function internally and give the outputs as follows -
- x == 0 (x equals to 0) - Runtime range error occurs and function returns -inf.
- x < 0 (x less than 0) - Runtime domain error occurs and function returns the nan.
Code Example
In the following coding example, we passed the double type value as 7.3 in the log() function and calculated its natural log.
The output comes out to be 1.987874.
Output
Code Examples with Different Datatypes as Parameters
1. Integers
In the following coding example, integer value 5 is passed as a parameter and its natural log comes out as 1.609438.
Output
2. Decimals (Float and Long Double Datatype)
The following code example passes the decimal values like float and long double.
Here the logf() and logl() functions are used to calculate the natural log of float and long double respectively.
Output
Conclusion
- log in C is used to compute the natural log of the given argument.
- The function log() is present in math.h library.
- Syntax of log in C is double log(double x).
- logf() and logl() can be used for float and long double values.