I agree with Collin in that this is a huge topic, and that there is probably no perfect solution. However, for those that are ok with an effective but imperfect solution, vacawama's answer is pleasantly simple. If you want to use your derivative function with some more math-y syntax, you could define an operator, fortunately Swift makes this exceptionally easy. Here is what I did:
I first defined an operator for just returning the function version of the derivative. I personally like the ➚ character for derivatives, but a very large portion of the existing unicode characters are valid Swift identifiers.
postfix operator ➚ {}
postfix func ➚(f: Double -> Double) -> (Double -> Double) {
let h = 0.00000000001
func de(input: Double) -> Double {
return (f(input + h) - f(input)) / h
}
return de
}
Next, lets define a function that we want to differentiate:
func f(x: Double) -> Double {
return x*x + 2*x + 3
}
This can be used as such: f➚
, which will return a an anonymous function which will be the derivative of f. If you wish to get f at a specific point (let x = 2, for example), you can call it like this: (f➚)(2)
I decided that I liked the operators, so I made another one to make that syntax look a little better:
infix operator ➚ { associativity left precedence 140 }
func ➚(left: Double -> Double, right: Double) -> Double {
return (f➚)(right)
}
The expression f➚2
will now return the same thing as (f➚)(2)
it just is more pleasant to use when you are doing math.
Good question, good answers everyone, I just thought I would tack something extra on. Let me know if you have any questions!