Evaluating a polynomial

Posted by hallakj
Announcements Last Post
SoC Curricula 09/30/2017 01:08PM
Demarcation or scoping of examinations and assessment 02/13/2017 07:59AM
School of Computing Short Learning Programmes 11/24/2014 08:37AM
Unisa contact information 07/28/2011 01:28PM
 Evaluating a polynomial July 30, 2007 10:13AM Registered: 13 years ago Posts: 24 Rating: 0
Hi All

We've received numerous enquiries from numerous students about Exercise 7.2, in particular how to translate a polynomial in string form to some sort of function so that you can determine its value for various values of x.

There are many ways to tackle this problem. The classic way of evaluating an arithmetic expression is to convert it into reverse Polish notation using a stack, and then pop each value, variable or operator from the stack and push the result back onto the stack. However, this method is overkill, since we are dealing with simple expressions (no parentheses, no division, and x being the only variable).

An easier way to determine what the value of the polynomial for a particular value of x is, is to keep the polynomial in its original form, i.e. as a string. Write a function that takes such a string and a double value (x) as parameters. In this function, search for the first occurrence of an operator (+, -, * or ^), and split the string into two pieces - before the operator and after it - and apply the function (recursively) to the two substrings. Add, subtract, multiply or raise to a power (as applicable), the two values returned by the recursive calls and return the result. However, if the remaining string consists simply of "x", return parameter x's value. Otherwise (i.e. there are no operators and no "x"s in the string) it must be a string representing a number, so convert it to a double and return that. (These are the two base cases of recursion.)

Hope that helps
Ken Halland
Sorry, only registered users may post in this forum.