This log1p()
function from java.lang.Math
library is used to calculate the natural logarithm (base e) of the sum specified value and 1. It is a static method so we will call this function by using the class name.
Syntax
public static double log1p(double value)
Parameters
Value whose logarithm is to be computed.
value
: an argument value of primitive double type.
Return Value
It will return the natural logarithm ln(x + 1)
.
Special Cases
The argument value should be of double
type.
- If the argument is a positive value, it will return
ln(x + 1)
. - If the argument is
NaN or less than -1
, it will returnNaN
. - If the argument is
positive infinity
, it will return the result asPositive Infinity
. - If the argument is a negative one, it will return
Negative Infinity
. - If the argument is
positive/negative zero
, it will returnZero
.
Explanation
The code snippet below covers all special cases mentioned above. Execute the code below and read the comments carefully to grab the whole concept.
// Load Math library
import java.lang.Math;
// Main class
public class AlgoIdeas {
// main driver class
public static void main(String args[])
{
double num1 = 23.45,
num2 = -145.25,
num3 = 1.0 / 0,
num4 = -1,
num5 = 0;
// positive double value
// output will be natural log of double type
System.out.println(Math.log1p(num1));
// positive zero
// output value will be Zero
System.out.println(Math.log1p(num5));
// negative double value
// output will be NAN
System.out.println(Math.log1p(num2));
// positive infinity
// output will be positive infinity
System.out.println(Math.log1p(num3));
// -1 as an argument
// output will be negative infinity
System.out.println(Math.log1p(num4));
}
}
- Line#2: Importing Math library into the program.
- Line#4: Main class to execute project code called. i.e. AlgoIdeas.
- Line#6:
main()
function to start program execution. - Line# 8-12: Defining multiple variables with different values to cover each use case.
- Line#15-27: Invoking
Math.log1p()
to calculate natural log parallel to each use case with different values.