Welcome! Log In Create A New Profile

Advanced

Evaluating a polynomial

Posted by hallakj 
Announcements Last Post
Announcement myUnisa availability 21 to 24 March 2019 03/17/2019 02:24PM
Announcement SoC Curricula 09/30/2017 01:08PM
Announcement Demarcation or scoping of examinations and assessment 02/13/2017 07:59AM
Announcement School of Computing Short Learning Programmes 11/24/2014 08:37AM
Announcement Unisa contact information 07/28/2011 01:28PM
Evaluating a polynomial
July 30, 2007 10:13AM
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.

Click here to login