Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package question2;
- /*represents a polynomial with a
- * degree and coefficients
- * can have a whole number degree
- * and a array of coefficients sized based on degree
- */
- public class Polynomial {
- int degree;
- double[] coefficients;
- /*
- * regular constructor for polynomial
- * only fills the degree variable of object
- */
- public Polynomial(int deg) {
- degree=deg;
- coefficients=new double[deg+1];
- }
- /*
- * copy constructor
- */
- public Polynomial(Polynomial p) {
- this.degree=p.degree;
- this.coefficients = p.coefficients.clone();
- }
- /*
- * sets value of coefficient in array, use in loop the index
- * is the number of coefficients in polynomial equation
- * based on standard polynomial equation
- */
- public void setCoefficient(int index, double value) {
- coefficients[index]=value;
- }
- /*
- * supply value of coefficient from array, use in loop
- */
- public double getCoefficient(int index) {
- double value=this.coefficients[index];
- return value;
- }
- /*
- * Calculates y of fully constructed polynomial given a x
- */
- public double evaluate(double x){
- double value=this.coefficients[0];
- for(int i=0; i<=this.degree; i++) {
- value=value+( (this.coefficients[i]) * (Math.pow(x, i)) );
- }
- return value;
- }
- /*
- * Determines if two polynomials are equal
- * compares degree and coefficients in order
- */
- public boolean equals(Polynomial poly) {
- if(poly.degree==this.degree) {
- for(int i=0; i<this.degree; i++) {
- if(this.coefficients[i]!=poly.coefficients[i]) {
- return false;
- }
- }
- return true;
- }
- return false;
- }
- /*
- * converts polynomial to string
- * as visual of equation
- */
- public String toString() {
- String out=""+this.coefficients[0];
- for(int i=1; i<=this.degree; i++) {
- if(this.coefficients[i]>0)
- out=out+" + ("+this.coefficients[i]+")x^"+i;
- }
- return out;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement