What is the log() function in Swift?
Overview
The log() function in Swift calculates the natural logarithm of a number. We can find it in Swift's Foundation library.
The mathematical representation of the log() function is as follows:
Syntax
The syntax for the log() function is as follows:
log(number)// The number should be floating, double, or real.
Parameter
This function requires a number for which the logarithm is to be calculated. It must be greater than 0.
Return value
log() returns the natural logarithm of the number sent as a parameter.
Example
The code below shows the use of the log() function in Swift.
import Swiftimport Foundation// Positive integerprint ("The value of log(4.0) : ", log(4.0));//Positive double valueprint ("The value of log(4.4) : ",log(4.4));//Eprint ("The value of log(M_E) : ",log(M_E));//Exceptional outputprint ("The value of log(-4.5) : ",log(-4.5));print ("The value of log(0.0) : ",log(0.0));
Explanation
- Line 2: We add the
Foundationheader required for thelog()function.
- Line 4: We calculate the natural log value of the positive integer using
log(). - Line 7: We calculate the natural log of the positive double value using
log().
- Line 10: We calculate the natural log of "E" using
log().
- Lines 13–15: We calculate the natural log of exceptional values using
log().