Advertisement
Guest User

Untitled

a guest
Jan 26th, 2020
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. package question2;
  2.  
  3. /*represents a polynomial with a
  4.  *  degree and coefficients
  5.  *  can have a whole number degree
  6.  *  and a array of coefficients sized based on degree
  7.  */
  8. public class Polynomial {
  9.  
  10.     int degree;
  11.     double[] coefficients;
  12.  
  13. /*
  14.  * regular constructor for polynomial
  15.  * only fills the degree variable of object
  16.  */
  17. public Polynomial(int deg) {
  18.     degree=deg;
  19.     coefficients=new double[deg+1];
  20. }
  21.  
  22. /*
  23.  * copy constructor
  24.  */
  25. public Polynomial(Polynomial p) {
  26.     this.degree=p.degree;
  27.     this.coefficients = p.coefficients.clone();
  28. }
  29.  
  30. /*
  31.  * sets value of coefficient in array, use in loop the index
  32.  * is the number of coefficients in polynomial equation
  33.  * based on standard polynomial equation
  34.  */
  35. public void setCoefficient(int index, double value) {
  36.     coefficients[index]=value;
  37. }
  38.  
  39. /*
  40.  * supply value of coefficient from array, use in loop
  41.  */
  42. public double getCoefficient(int index) {
  43.     double value=this.coefficients[index];
  44.     return value;
  45. }
  46.  
  47. /*
  48.  * Calculates y of fully constructed polynomial given a x
  49.  */
  50. public double evaluate(double x){
  51.     double value=this.coefficients[0];
  52.     for(int i=0; i<=this.degree; i++) {
  53.         value=value+(  (this.coefficients[i])  *   (Math.pow(x, i))    );
  54.     }
  55.     return value;
  56.    
  57. }
  58.  
  59. /*
  60.  * Determines if two polynomials are equal
  61.  * compares degree and coefficients in order
  62.  */
  63. public boolean equals(Polynomial poly) {
  64.    
  65.     if(poly.degree==this.degree) {
  66.         for(int i=0; i<this.degree; i++) {
  67.             if(this.coefficients[i]!=poly.coefficients[i]) {
  68.                 return false;
  69.             }
  70.         }
  71.         return true;
  72.     }
  73.     return false;
  74. }
  75.    
  76.  
  77. /*
  78.  * converts polynomial to string
  79.  * as visual of equation
  80.  */
  81. public String toString() {
  82.     String out=""+this.coefficients[0];
  83.    
  84.    
  85.     for(int i=1; i<=this.degree; i++) {
  86.         if(this.coefficients[i]>0)
  87.         out=out+" + ("+this.coefficients[i]+")x^"+i;
  88.     }
  89.     return out;
  90. }
  91.  
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement