I want to calculate log(2)8
in Swift without import modules. I can't find any function in the Document.
Logarithms were invented in the 17th century as a calculation tool by Scottish mathematician John Napier (1550 to 1617), who coined the term from the Greek words for ratio (logos) and number (arithmos).
Using Logarithmic Functions Much of the power of logarithms is their usefulness in solving exponential equations. Some examples of this include sound (decibel measures), earthquakes (Richter scale), the brightness of stars, and chemistry (pH balance, a measure of acidity and alkalinity).
In mathematics, the logarithm is the inverse function to exponentiation. That means the logarithm of a given number x is the exponent to which another fixed number, the base b, must be raised, to produce that number x.
When calculus is involved, natural logarithms are usually used. For special purposes, other logarithms are used, mainly logarithms with base 10 or with base 2.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With