Create a class Polynomial that is used to evaluate a polynom

Create a class Polynomial that is used to evaluate a polynomial function of x: A polynomial has the general form of: P(x) = a_n. x^n + a_n-1. x^n-1 ... a_2. x^1 + a_2. x^1 + a_0. x^0 The coefficients a_i are floating-point numbers, the exponents of x are integers, and the largest exponent n - called the degree of the polynomial - is greater than or equal to 0. The class has the attributes: degree - the value of the largest exponent n coefficients - an array of the coefficients a_i and the following methods: Polynomial (max) - a constructor that creates a polynomial of degree max whose coefficients are all 0 setConstant(i, value) - sets the coefficient a_i to value evaluate(x) - returns the value of the polynomial for the given value x. For example, the polynomial P(x) = 3 + 5x + 2x^3 is of degree 3 and has coefficients a_0 = 3, a_1 = 5, a_2 = 0, a_3 = 2. The invocation evaluate (7) computes 3 + 5 times 7 + 0 times 7^2 + 2 times 7^3, which is 3 + 35 + 0 + 686 and returns the result 724. Another example, the polynomial x^3 + 3x^2 + 2 has a degree of 3 and can represent by the following array of coefficients. {2, 0, 3, 1}

Solution

import java.util.*;

public class Polynomial
{
int max;
static int array[]= new int[100];

private Polynomial(int max)
{
for(int j=0;j<=max;j++)
{
array[j]=0;
}
}
  
void secConstant(int i,int value)
{
array[i]=value;
}
double evaluate(double x)
{
double px=0;
System.out.println(max);
for(int i=0;i<=max;i++)
{
px=px+array[i]*(pow1(x,i));
}
return px;
}
double pow1(double x,int j)
{
double s=1;
int i;
for(i=0;i<j;i++)s=s*x;
return s;
}
public static void main(String[] args)
{
System.out.println(\"Enter Degree of polynomial\");
Scanner scan=new Scanner(System.in);
int m=scan.nextInt(),i,value;
Polynomial p=new Polynomial(m);
p.max=m;
System.out.println(\"Enter Coefficients for polynomial from a0 to an:\");
for(i=0;i<=m;i++)
{
value=scan.nextInt();
p.secConstant(i, value);
}
System.out.println(\"Enter X value\");
double x=scan.nextInt();
System.out.println(\"P(x) is:\"+p.evaluate(x));
}
}

output:-

run:
Enter Degree of polynomial
3
Enter Coefficients for polynomial from a0 to an:
3 5 0 2
Enter X value
7
3
P(x) is:724.0
BUILD SUCCESSFUL (total time: 11 seconds)

 Create a class Polynomial that is used to evaluate a polynomial function of x: A polynomial has the general form of: P(x) = a_n. x^n + a_n-1. x^n-1 ... a_2. x^
 Create a class Polynomial that is used to evaluate a polynomial function of x: A polynomial has the general form of: P(x) = a_n. x^n + a_n-1. x^n-1 ... a_2. x^

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site