Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package polymoialtest;
- public class Polynomial {
- private double [] coef;
- //coef[i] is the coefficient of x to the ith power
- public Polynomial (int degree) {
- coef = new double[degree+1];
- }
- //set the value of the coefficient of x to the ith
- public void setCoef(double value, int i) {
- if ( i >= 0 && i < coef.length ) {
- coef[i] = value;
- }
- }
- public double getCoef(int i) {
- return coef[i];
- }
- public int getLength() {
- return coef.length;
- }
- public double eval( double x) {
- double result = 0;
- double power = 1;
- for (int i= 1; i <= coef.length; i++) {
- result = result + power * coef[i-1];
- power = power * x;
- }
- return result;
- }
- public Polynomial plus( Polynomial addend) {
- int lengthA = this.getLength();
- int lengthB = addend.getLength();
- int largest = lengthA > lengthB ? lengthA : lengthB;
- Polynomial r = new Polynomial(largest - 1);
- for (int i = 0;i < largest; i++) {
- if (i < lengthA && i < lengthB)
- r.setCoef(addend.getCoef(i) + this.getCoef(i),i);
- else if (i < lengthA)
- r.setCoef(this.getCoef(i),i);
- else if (i < lengthB)
- r.setCoef(addend.getCoef(i),i);
- }
- return r;
- }
- public String toString(){
- String output = "";
- for (int i = coef.length - 1; i > 0;i--) {
- if (coef[i] != 0 && coef[i] != 1) {
- if (i > 1)
- output += String.format("%.1fx^%d + ",coef[i],i);
- else
- output += String.format("%.1fx + ",coef[1]);
- } else if (coef[i] == 1) {
- if (i > 1)
- output += String.format("x^%d + ",i);
- else
- output += String.format("x + ");
- }
- }
- output += String.format("%.1f",coef[0]);
- return output;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement