calculate the derivative in swift

To calculate the derivative of a function in Swift, we first need to define the function. Suppose our function is f(x) = x^2 + 3x + 2. We define this function as follows:

main.swift
func f(x: Double) -> Double {
    return x*x + 3*x + 2
}
57 chars
4 lines

Now that we have defined our function, we can calculate its derivative using the central difference method. The central difference method uses two points on either side of the point we want to calculate the derivative at, and computes the slope between these points.

main.swift
func derivative(f: (Double) -> Double, x: Double) -> Double {
    let h = 0.0001 // small number for computing the slope
    return (f(x + h) - f(x - h)) / (2 * h)
}
166 chars
5 lines

We can now call this function to calculate the derivative of our function f(x) at a particular point. For example:

main.swift
let x = 2.0
let df_dx = derivative(f: f, x: x)
print(df_dx) // Output: 7.000199999999293
89 chars
4 lines

Thus, the derivative of our function f(x) at x=2 is approximately 7.

gistlibby LogSnag