Swift Tutorial Swift References

Swift - log2() Function



The Swift log2() function returns the base-2 logarithm of a given number.

Syntax

In Foundation framework, it is defined as follows:

public func log2(_ x: CGFloat) -> CGFloat
public func log2(_ x: Float) -> Float
public func log2(_ x: Float80) -> Float80
public func log2(_ __x: Double) -> Double

Parameters

x Specify the number.

Return Value

Returns the base-2 logarithm of a given number.
If the x is negative, it returns -nan.
If the x is 0, it returns -inf.

Example:

In the example below, log2() function is used to calculate the base-2 logarithm of a given number.

import Foundation

print("log2(0.0) = \(log2(0.0))")
print("log2(1.0) = \(log2(1.0))")
print("log2(2.0) = \(log2(2.0))")
print("log2(50.0) = \(log2(50.0))")
print("log2(-1.0) = \(log2(-1.0))")

The output of the above code will be:

log2(0.0) = -inf
log2(1.0) = 0.0
log2(2.0) = 1.0
log2(50.0) = 5.643856189774724
log2(-1.0) = -nan

❮ Swift Math Functions