iPhone - how can I insert a mathematical function through a textfield?
I want to make an iphone program that makes the graph of a mathematic function, like sin(x)
.
So, I want to put the mathematical expression sin(x)
in a UITextfield and then take it and use it li开发者_开发技巧ke a function.
Does anyone know how to do this?
You have two problems:
- You need to evaluate an
NSString
as if it were a mathematical equation and obtain a number from it. - You need to plot some numbers on a graph.
Fortunately, there are projects out there to help you with this:
- DDMathParser - a library I wrote for evaluating strings as mathematical expressions. There are other alternatives, such as ANExpressionParser and GCMathParser, but ANEP doesn't always parse things correctly (ex: -2 ** -2 should be -0.25, and it parses it as 0.25) and GCMathParser isn't extensible and is no longer under development. However, GCMathParser is insanely fast. It is much faster than
DDMathParser
(by a couple orders of magnitude), but DDMathParser will still parse things in a fraction of a second. - Core Plot - A pretty awesome graphing framework. I haven't had occasion to use it myself, but it's also under active development and has a pretty solid community of users. I've heard nothing but good things about it.
You could convert the text expression into Javascript ("sin" -> "Math.sin", etc.), run the Javascript code inside a UIWebView, get a string result back, and convert it into numeric data.
A UILabel with text "sin(" followed by UITextFied (with placeholder text) where user enters the value of x, followed by another UILabel with closing brace ")".
精彩评论