A First Function Plotter
As it stands as of yesterday, we can only simplify mathematical expression without variables. My first goals for today are two-fold: less global variables (overall) and more variables (in the expression, at least one…).
I first found that I could tuck vString and its iterator into function parameters fairly easily, but they had to be part of the parameter lists for parse(), gettok() and shift(). I then found it was quite easy to add a variable token, tVar, to the list of tokens (the sixteenth token with ID 15) and modify the algorithm to push the value of ‘x’ onto the val stack when encountered. Here is a summary of the changes I made to get this new code.
First, the new prototypes are int parse(double x, std::vector<char>& vS, std::vector<char>::iterator& vSIter) int gettok(std::vector<char>& vS, std::vector<char>::iterator& vSIter) int
shift(double x, std::vector<char>& vS, std::vector<char>::iterator& vSIter) The main() function has been modified to declare the expression vector and its iterator and to fetch the value of the variable from the user:
Thus, we can now do stuff like this:
I’ve also added the Boolean flag erCh for turning on/off the error checking/debugging statements.
Now, how about nesting more global variables and working towards computing lots of input/output pairs with the ultimate goal of making a function plotter? As we’ll need to introduce the OpenGL functions, most of the action will move to the display function, as shown below. As it stands, this prototype will graph any function it can parse (parse() was modified to return a doublethe value of f(x).) But there are various quirky aspects I have yet to iron out: like how it sometimes erases a plot before you can see itOpenGL pipeline issues. Still, it’s a start!
The simple evaluate function above has been adapted to loop within the OpenGL framework to sample the function in/out values at 11 evenly spaced points from x = -5 to 5 and then these are rescaled to fit the given window. The expression string is entered once and then you need to reset the opr and val stacks for each parse:
I thickened the line width to 2.0 and did some color variations, so when I enter x^2 as my expression, here’s the plot:
|
|