Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate Mathematical Function from String [closed]

Tags:

c

math

parsing

Can you give me some ideas about how can I make a simple mathematical expression parser in C?

User enters a mathematical function in a string and from the string I want to create the function in C. eg. x + sin(2*x)

-> return x + sin(2x);

Thanks in advance.

like image 522
bokarinho Avatar asked Apr 02 '12 13:04

bokarinho


People also ask

How do you evaluate a string as a mathematical expression in JavaScript?

To evaluate a string as a mathematical expression in JavaScript, we can use the mathjs library. import { evaluate } from "mathjs"; const n = evaluate("1.2 * (2 + 4.5)"); to call evaluate with the math expression we want to evaluate. The return value is the value of the expression after evaluating as a number.


2 Answers

You can parse the expression based "Shunting-Yard Algorithm" http://en.wikipedia.org/wiki/Shunting-yard_algorithm. You will need to extend to handle the function calls such as sin, cos etc...

like image 179
anilsinaci Avatar answered Oct 02 '22 17:10

anilsinaci


This is not a simple thing to do at all, in face, it's a hard thing. You need a full grammar parser, combined with pre-defined constants/functions (sin, log, pi, etc).

If you have no extensive previous experience with C I would disrecommend doing this, but if you really want to do this look at recursive descent parsing which is arguably the easiest way to do this (without putting a burden on the user, like reverse polish notation).

Last but not least you say you want to create a C function from the user-generated input. This is almost always a wrong thing to do - generating code from user input, instead the easiest approach is pre-processing to create a intermediate representation that can be efficiently executed.

like image 45
orlp Avatar answered Oct 02 '22 15:10

orlp