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:
Note: We need to import
Foundation
in our code to use thelog2()
function. We can import it like usingimport Foundation
.
log2(number)
The number whose logarithm we have to calculate should have the following properties:
The function returns the logarithm of the given number.
import Foundation// Using a positive integerprint ("log2(4.0) = ", log2(4.0));// Using a positive floatprint ("log2(4.4) = ",log2(4.4));// Using a value of 2print ("log2(2.0) = ",log2(2.0));// Using values which raise exceptionsprint ("log2(-4.5) = ",log2(-4.5));print ("log2(0.0) = ",log2(0.0));
Foundation
header required to use the log2()
function.log2()
function to calculate the logarithm of a positive integer with the base, 2.log2()
function to calculate the logarithm of a positive float with the base, 2.log2()
function to calculate the logarithm of the number 2
with the base, 2.log2()
function to calculate the logarithm of exceptional values with the base, 2.