Thread: Input and Parse Math Functions

1. Input and Parse Math Functions

I'm in a numerical analysis class and our assignment is to use Newton's method to estimate roots of a fuction after n steps. That is the easy part, but our professor decided that he wants to be able to input any function ( for example f(x) = 23x^4-3x^2-35x+2 ) at a promt and have our program still work. He doesn't care if we use any outside libraries as long as we don't use them for the method itself. Anyone have recommendations for a library (I can do it in C or C++) that will allow a user to enter a function like that and use it in calculations?

2. No, but you could ease the process with lex+yacc (or rather the modern implementations, flex and bison). Both programs generate C code that you compile with your program. http://ds9a.nl/lex-yacc/cvs/lex-yacc-howto.html

3. If they're always expressed as polynomials, all you need is an array, a loop and a value for x

Eg.
double terms[5];

Then parse the string to get
terms[4] = 23;
terms[3] = 0;
terms[2] = -3;
terms[1] = -35;
terms[0] = 2;

4. Originally Posted by Salem
If they're always expressed as polynomials, all you need is an array, a loop and a value for x
I don't think they will be. He should be able to input any function that is continuous and differentiable over a given range. That's why I was hoping someone out there already wrote a library that would process the input for me.

No, but you could ease the process with lex+yacc (or rather the modern implementations, flex and bison).
I'm familiar with these but I've never used them. I didn't think these could parse input in a program for use at runtime though. I'll look into it.

5. If your professor allows it, you should just input first the degree of the polynomial, and then the coefficients in a loop. There's no point in getting bogged down in how to parse a string containing a polynomial when that has nothing to do with the mathematics involved.

6. Originally Posted by TheSquid
I don't think they will be. He should be able to input any function that is continuous and differentiable over a given range. That's why I was hoping someone out there already wrote a library that would process the input for me.

I'm familiar with these but I've never used them. I didn't think these could parse input in a program for use at runtime though. I'll look into it.
Sure they can, that's how compilers work.

--
Mats