Convert string to math equation?

I'm new at this. I want to convert a string to a mathematical equation to input my graphing calculator for example:

cos(x+1)+ ln(x)

so we will convert it to

 double x = -10; for (int i=0; i<100; i++) { double y=Math.cos(x+1)+Math.log(x) x=x+0.5 } 

so i want to know y conversion method

thank

+2
java android
Jan 15 '14 at
source share
5 answers

In java there is no "ready-made" solution for this.

However: Required answer: google β†’ "convert string to mathematical expression java" The first few answers are pretty good (for example: What is a good library for parsing mathematical expressions in java? ) Required answer 2: There are many libraries on the network for converting strings to mathematical expressions, naming them will be inaccurate in accordance with the rules, so I offer the "Mandatory answer" the first few calls.

Also, most likely, you will be better off by choosing the format you receive and write your own parser for this format.

+2
Jan 15 '14 at 15:00
source share

First you need to write a parser by building a tree of your input expression. Then you can use this to generate your code.

But "I'm a beginner" is not very good at writing parsers :)

+1
Jan 15 '14 at 14:50
source share

You should have a small formal grammar describing the syntax of your expression, then you need to convert the expression of the input string into an AST representation.

http://en.wikipedia.org/wiki/Abstract_syntax_tree

Finally, you need to have a procedure to evaluate AST for certain parameter values.

+1
Jan 15 '14 at
source share

In pure Java, this is not easy. There are many other similar questions with good answers. Most solutions involve evaluating the expression in the interpreter or analyzing the expression (there are some libraries for this) or even debugging. I don’t know what is available on Android specifically for this, but there are tons of good answers for this in SO. Here's a good way for you: Evaluating a mathematical expression given in string form

+1
Jan 15 '14 at
source share

I did this exact thing using NCalc . I went through the user string expression, replaced the variables with the values ​​I am evaluating, and then using the Evaluate method and parsing it with a double.

 private double Function(double t, double y) { NCalc.Expression expression = new NCalc.Expression(this.Expression); expression.Parameters["t"] = t; expression.Parameters["y"] = y; double value; double.TryParse(expression.Evaluate().ToString(), out value); return value; } 

For example, given the inputs t = .5 and y = 1 and the expression "4 * y + Tan (2 * t)", we will evaluate the string "4 * 1 + Tan (2 * .5)" using NCalc.

This is not ideal, NCalc throws an exception if it cannot parse the user string or that the data types are different. I am working on polishing it.

I also asked the same question here .

0
Sep 03 '15 at 15:01
source share



All Articles