package polinoms; import java.util.Vector; public class Polinom implements Cloneable { private int degree; private Vector<Number> coef = null; public Polinom (Number [] array) { degree = array.length-1; coef = new Vector<Number>(array.length); for(int i=0; i<array.length; i++) coef.add(array[i]); } public Polinom (Polinom p) { // Copy constructor degree = p.degree; coef = (Vector<Number>)p.coef.clone(); } public Polinom (Vector<Number> v) { degree = v.size(); coef = (Vector<Number>)v.clone(); } private Polinom (int degree) { this.degree = degree; coef = new Vector<Number>(degree+1); for(int i=0; i<=degree; i++) coef.add(0); } public Number value(Number x) { double result = coef.elementAt(degree).doubleValue(); double dx = x.doubleValue(); for(int i=degree-1; i>=0; i--) { result = result * dx + coef.elementAt(i).doubleValue(); } return new Double(result); } public Polinom add(Polinom other) { Polinom result; Polinom second; if(this.degree >= other.degree) { result = new Polinom(this); second = other; } else { result = new Polinom(other); second = this; } double d; for(int i=0; i<=second.degree; i++) { d = result.coef.elementAt(i).doubleValue() + second.coef.elementAt(i).doubleValue(); coef.set(i, d); } return result; } public Polinom mult(Polinom other) { Polinom result = new Polinom(this.degree+other.degree); double d; for(int i=0; i<=this.degree; i++) for(int j=0; j<=other.degree; j++) { d = result.coef.elementAt(i+j).doubleValue() + this.coef.elementAt(i).doubleValue() * other.coef.elementAt(j).doubleValue(); result.coef.setElementAt(d, i+j); } return result; } public boolean equals(Object o) { if(o == null) return false; if(!(o instanceof Polinom)) return false; if(o == this) return true; Polinom tmp = (Polinom)o; return degree == tmp.degree && coef.equals(tmp.coef); } public Object clone() { Polinom result = null; try { result = (Polinom) super.clone(); } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } result.coef = (Vector<Number>) coef.clone(); return result; } public String toString() { StringBuffer str = new StringBuffer(""); for(int i=degree; i>0; i--) { str.append(coef.elementAt(i) + "*x^" + i + " + "); } str.append(coef.elementAt(0)); return str.toString(); } }