Does Swift has built-in logarithm function?
You can use the log2(:Double)
or log2f(:Float)
methods from the documentation, available by e.g. importing UIKit
or Foundation
:
func log2(x: Double) -> Doublefunc log2f(x: Float) -> Float
E.g., in a Playground
print(log2(8.0)) // 3.0
(Edit addition w.r.t. your comment below)
If you want to compute your custom-base log function, you can make use of the following change-of-base relation for logarithms
Hence, for e.g. calculating log3
, you could write the following function
func log3(val: Double) -> Double { return log(val)/log(3.0)}print(log3(9.0)) // "2.0"
Or, simply a custom-base log function:
func logC(val: Double, forBase base: Double) -> Double { return log(val)/log(base)}print(logC(9.0, forBase: 3.0)) // "2.0"print(logC(16.0, forBase: 4.0)) // "2.0"