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:

log(x)=loge(x)=ln(x)log(x) = log_e(x) = ln(x)

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 Swift
import Foundation
// Positive integer
print ("The value of log(4.0) : ", log(4.0));
//Positive double value
print ("The value of log(4.4) : ",log(4.4));
//E
print ("The value of log(M_E) : ",log(M_E));
//Exceptional output
print ("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 Foundation header required for the log() 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().