Does Swift Has Built-in Logarithm Function?

Does Swift Has Built-in Logarithm Function?

I want to calculate log(2)8 in Swift without import modules. I can't find any function in the Document.

1 Answer

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) -> Double
func 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"
7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.