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

enter image description here

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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