C question

Associate
Joined
30 Sep 2004
Posts
1,038
Location
Colchester, Essex
If I have a mathematical function saved in a string, like:
Code:
(x+3)^3+x+24x-3+x^(3+24x)+sin(x)
would it be possible to convert it into something useable by C (math.h functions) such as:
Code:
pow(x+3,3)+x+24*x-3+pow(x,3+24x)+sin(x)
if it is, could someone please point me in the right direction

Thanks
 
You'll need to either write an expression parser or find a library that can do it for you.

I don't know of any such parsers written in C, but have a look on Google for "mathematical expression parser" or something similar.

It's an interesting project to try and tackle though, so you could do it yourself :)
 
Agreed, you'd have to run through each character in the string to find matching patterns (you can use regular expressions to help with this) and convert those to the appropriate functions (or rather, you'd find say the word 'sin' and ignore that but find it's parameters (x) and pass that into the math sine function)
 
Agreed, you'd have to run through each character in the string to find matching patterns (you can use regular expressions to help with this) and convert those to the appropriate functions (or rather, you'd find say the word 'sin' and ignore that but find it's parameters (x) and pass that into the math sine function)

Regular expressions aren't suitable for this kind of problem. The best approach is to construct an expression tree from the string:

http://www.brpreiss.com/books/opus5/html/page264.html

The parser will need to take account of operator precedences and parentheses, of course.
 
Back
Top Bottom