What is the log2() function in Swift?

Overview

The log2() function in Swift uses the base, 2, to calculate a number's logarithm.

Figure 1 shows the mathematical representation of the log2() function:

Mathematical representation of the log2() function

Note: We need to import Foundation in our code to use the log2() function. We can import it like using import Foundation.

Syntax

log2(number)

Parameters

The number whose logarithm we have to calculate should have the following properties:

  • It should be greater than 0.
  • It should be either an integer, float, or double.

Return value

The function returns the logarithm of the given number.

Example

import Foundation
// Using a positive integer
print ("log2(4.0) = ", log2(4.0));
// Using a positive float
print ("log2(4.4) = ",log2(4.4));
// Using a value of 2
print ("log2(2.0) = ",log2(2.0));
// Using values which raise exceptions
print ("log2(-4.5) = ",log2(-4.5));
print ("log2(0.0) = ",log2(0.0));

Explanation

  • Line 2: We add the Foundation header required to use the log2() function.
  • Lines 4: We use the log2() function to calculate the logarithm of a positive integer with the base, 2.
  • Line 7: We use the log2() function to calculate the logarithm of a positive float with the base, 2.
  • Line 10: We use the log2() function to calculate the logarithm of the number 2 with the base, 2.
  • Lines 13–15: We use the log2() function to calculate the logarithm of exceptional values with the base, 2.

Free Resources