User inputed f(x) usable in swift

129 Views Asked by At

I'm working on some calculus functions in swift. The main barrier I have to all of them is taking some kind of user input system and being able to use that in the function. For example, if I can translate what the user inputs into a swift acceptable mathematical expression then I can do all the calculus based things I need with pretty simple functions like:

Derivitive:

func derivativeOf(fn: (Double)->Double, atX x: Double) -> Double {
    let h = 0.0000001
    return (fn(x + h) - fn(x))/h
}

Limit

 func limit(fn: (Double)->Double, atX x: Double) -> Double {
    let modifier = 0.0000001
    return (fn(x + modifier)) 
}

Ect..

What strategy of user input can I do to make swift be clear on the Double to Double functions my calculus functions need? How do I translate trig functions, constants, exponents, ect. well?

1

There are 1 best solutions below

3
On

Looks great! In the playground, saying:

func derivativeOf(fn: (Double)->Double, atX x: Double) -> Double {
    let h = 0.0000001
    return (fn(x + h) - fn(x))/h
}

derivativeOf({ (x) -> Double in
    return x * x
}, atX: 5)

Gives 10.000001 something (it's an approximation), which is indeed the correct answer! Looks great, but to take advantage of Swift's trailing closure, I would switch the two parameters around, so the fn parameter is at the end.

That way, it'll be more like this:

func derivativeOf(atX x: Double, fn: (Double)->Double) -> Double {
    let h = 0.0000001
    return (fn(x + h) - fn(x))/h
}

derivativeOf(atX: 5) { x in
    return x*x
}

It's so much more intuitive to read the function call this way.

My thoughts on how you have the user input the function is by having a text field with a label on top that says, "given x, the equation is:"

and the user would write "x * x". But, because Swift is a compiled language, we can't just convert a string into compilable code.

However, I was thinking something else. Instead of having the user write "x * x", you could have them write "5 * 5" and compute the derivative by doing a forced downcast from string "5" to an Int type. Just an idea.

Here's also a plausible solution. I'm looking into the Objective C implementation and here's one way:

Convert NSString of a math equation to a value