Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Swift has built-in logarithm function?

Tags:

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

like image 903
Zentopia Avatar asked Mar 09 '16 08:03

Zentopia


People also ask

Where does the log function come from?

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).

Where are log functions used?

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).

What type of functions are logs?

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.

Is log used in calculus?

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.


Video Answer


1 Answers

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" 
like image 109
dfrib Avatar answered Sep 20 '22 04:09

dfrib