Question: Write a C program, polynomial.h, containing the following polynomial operation functions: 1. float horner(float p[], int n, float x), which computes and returns the value
Write a C program, polynomial.h, containing the following polynomial operation functions:
1. float horner(float p[], int n, float x), which computes and returns the value of the following (n-1)-th degree polynomial p(x) of coefficients p[0], , p[n-1]. p(x) = p[0]xn-1 + p[1]xn-2 ++ p[n-2]x1 + p[n-1]x0
2. void derivative(float p[], int n, float d[]), which computes the derivative of input (n-1)-th degree polynomial by p[], output the derivative of (n-2)-th degree polynomial to array d[]. The derivative of the above polynomial p(x) is as follows. p(x) = (n-1)* p[0]xn-2+ (n-2)p[1]xn-3 ++ p[n-2]x0
3. float newton(float p[], int n, float x0), which finds an approximate real root x of polynomial p(x) using the Newtons method with start position x0. Use the fault tolerant 1e-6 (or 0.000001) as a stop condition, i.e., if r is the actual root, stop the iteration if |x-r|<1e-6 or |p(x)| < 1e-6.
polynomial_main.c
#include
#include
#include
#include "polynomial.h"
void display_polynomial(float p[], int n, float x)
{
int i;
for (i=0; i if (p[i] > EPSILON && i !=0) printf("+"); printf("%.2f*%.2f^%d", p[i], x, n-i-1); } } int main(int argc, char *argv[]) { int n = 4; float p[] = {1, 2, 3, 4}; int m = 3; float x[] = {0,1,10}; // test display and horner functions int i; for (i=0; i printf("p(%.2f)=", x[i]); display_polynomial(p, n, x[i]); printf("="); printf("%.2f ", horner(p, n, x[i])); } // test derivative function float d[n-1]; derivative(p, n, d); for (i=0; i printf("d(%.2f)=", x[i]); display_polynomial(d, n-1, x[i]); printf("="); printf("%.2f ", horner(d, n-1, x[i])); } // test newton function float x0=-2; float root = newton(p, n, x0); printf("root=%.2f ", root); printf("p(%.2f)=%.2f ", root, horner(p, n, root)); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
