In: Computer Science
In c++
This question is relevant if you implemented a polynomial that included some calculus-based operations such as derivative and integral. Write a new function that meets the following specification:
double slope(const polynomial& p, double x)
// POSTCONDITION: The return value is equal to the slope of the
// polynomial p, evaluated at the point x.
Solution:
In this question, we have to write the function which returns
the slope of a given polynomial. so, here we calculate the
differential calculus.
The formula for differential calculus is as
follows:
If f(x) = axn then, f'(x) = f(x) dx = a*nxn-1 where n>=0 and a is coefficient (a>=1) .
Suppose f(x) = 2x2+4x. and x =2.
Then the slope will be f'(x) = 2x2 dx + 4x dx
f'(x) = 2*2 x2-1 + 4x1-1
f'(x) = 4x + 4
put x = 2,
f'(2) = 4 * 2 + 4 = 8 + 4 = 12. (Slope of the polynomial)
.
C++ Function:
// the term_calulate function calculate the derivative of each term of polynomial.
double term_calulate(string pTerm, double val)
{
// Get coefficient
string coeffStr = "";
int i;
for (i = 0; pTerm[i] != 'x'; i++)
coeffStr.push_back(pTerm[i]);
double coeff = atol(coeffStr.c_str());
// Get Power after skipping 2 characters for x and
^
string powStr = "";
for (i = i + 2; i != pTerm.size(); i++)
powStr.push_back(pTerm[i]);
double power = atol(powStr.c_str());
// For ax^n, we return a(n-1)x^(n-1)
return coeff * power * pow(val, power - 1);
}
// The slope function takes the polynomial and value of point x as input and return the slope value as output.
double slope(string& poly, double x)
{
double ans = 0.0;
// Use istringstream to get input in tokens
istringstream is(poly);
string pTerm;
while (is >> pTerm) {
// If the token is '+' then
continue with the string
if (pTerm == "+")
continue;
// Else find the derivative of
particular term
else
ans = (ans +
term_calulate(pTerm, x));
}
return ans;
}
Here we use the 2 functions the first function calculates the
derivative of each term and the second one calculate the slope of
the polynomial.