Полиномиальный композитный метод Java - PullRequest
0 голосов
/ 28 мая 2011

Эй, я делаю составной метод для полиномов в Java, и у меня возникли некоторые проблемы.Это мой код до сих пор, и я только что потерял ...

public class Polynomial 
{ 
    final static private int mantissa = 52;
    final static private double epsilon = Math.pow(2.0, -mantissa);
    private double coefficient = 0.0;
    private int power = 0;
    private Polynomial successor = null;

    public Polynomial(double coefficient, int power) 
    {
        if (Double.isNaN(coefficient))return;        
        if (Math.abs(coefficient) < epsilon)return;        
        if (power < 0)return;        
        this.coefficient = coefficient;
        this.power = power;
    }

    /* conditions
    this(X) => sum(coefficient(i)*X^i:for(i=degree;i>=0;i--)) && X^0=1
    this.degree()==this.power==highestPower
    this.highestPoweredCoefficient==this.coefficient
    this.successor!=null links to terms whose powers uniquely decrease
    Polynomial(0.0,0)=(coefficient=0.0,power=0,successor=null)==0.0
    if (coefficient==NaN) coefficient=0.0
    if (abs(coefficient)<epsilon)) coefficient=0.0
    if (power<0) power=0
    if (this.degree()==0) abs(coefficient(0))>=0.0
    if (this.degree()>0) abs(coefficient(i))>=epsilon for all i>=0
     */  
    private static void add(Polynomial polynomial, double coefficient, int power) 
    {
        // This part is given to us 
        if (polynomial == null) return;
        if (Math.abs(coefficient) < epsilon) coefficient = 0.0;
        if (coefficient == 0.0) return;
        if (power < 0) return; 
        // End of given code.
        if (polynomial.coefficient == 0.0)
        {
            polynomial.coefficient = coefficient;
            polynomial.power = power;
            return;
        }

        if (polynomial.power == power)
        {    
            polynomial.coefficient += coefficient;
            if (Math.abs(polynomial.coefficient) < epsilon)
            polynomial.coefficient = 0.0;

            if (polynomial.coefficient != 0.0 || polynomial.power == 0) return;
            if (polynomial.successor == null)
            {
                polynomial.power = 0;
                return;
            }
                polynomial.coefficient = polynomial.successor.coefficient;
            polynomial.power = polynomial.successor.power;
            polynomial.successor = polynomial.successor.successor;
            return;
        }      
        // sets up variables used.
        Polynomial old = null;
        Polynomial checker = polynomial;

        // goes through polynomial looking for the right place.
        while (checker != null)
        {
            if (checker.power <= power)
            { 
                break; //breaks the loop
            }
            old = checker;
            checker = checker.successor;
        }

        //
        if (old == null)
        {
            Polynomial node = new Polynomial(0.0,0); //creates a new node for insertion
            node.coefficient = polynomial.coefficient;
            node.power = polynomial.power;
            node.successor = polynomial.successor;
            polynomial.coefficient = coefficient;
            polynomial.power = power;
            polynomial.successor = node;
            return; 
        }
        //
        if (checker == null || checker.power < power)
        {
            Polynomial node = new Polynomial(0.0,0); //sets a node for insertion
            node.coefficient = coefficient;
            node.power = power;
            node.successor = checker;
            old.successor = node;
            return;
        }
        coefficient += checker.coefficient;
        if (Math.abs(coefficient) < epsilon) coefficient = 0.0;
        if (coefficient == 0.0)
            old.successor = checker.successor;
        else
            checker.coefficient = coefficient;
    }

    final public int cardinality() {
        int count = 1; 
        Polynomial traverser = this.successor; 
        while (traverser != null) 
        {                                     //THIS METHOD IS GIVEN TO US!
            count++;
            traverser = traverser.successor;
        }
        return count;
    }


    final public Polynomial clone() {
        Polynomial result = new Polynomial(0.0, 0);

        result.coefficient = this.coefficient;

        result.power = this.power;

        Polynomial traverserThis = this;

        Polynomial traverserResult = result;     //THIS METHOD IS GIVEN TO US!

        while (traverserThis.successor != null) {
            traverserResult.successor = new Polynomial(0.0, 0);
            traverserThis = traverserThis.successor;
            traverserResult = traverserResult.successor;
            traverserResult.coefficient = traverserThis.coefficient;
            traverserResult.power = traverserThis.power;
        }

        return result;
    }


    final public double coefficient(int power) {
        if (power < 0) {
            return 0.0;
        }

        Polynomial traverser = this;

        do {
            if (traverser.power < power) {
                return 0.0;
            }
            if (traverser.power == power) { //THIS METHOD IS GIVEN TO US
                return traverser.coefficient;
            }
            traverser = traverser.successor;
        } while (traverser != null);

        return 0.0;
    }

   //Method done by Callum
        final public Polynomial composite(Polynomial that)
        {
               if (that == null) 
            {
                return null;
            }     
            Polynomial result = new Polynomial(0.0, 0); //the result polynomial
            Polynomial current = this.clone(); //current is a copy of 'this' used for moving through
                                               // the loop. 
            Polynomial tempHolder2 = that;
            Polynomial tempHolder = new Polynomial(0.0, 0); //just a temporary holding polynomial
            Polynomial thatNew = that.clone(); //another clone used for iteration.     
            while(current != null)
            {                
                for( int i = 1; i <= current.power; i++)
                {
                  tempHolder2 = tempHolder2.times(thatNew);  
                }       
                tempHolder.coefficient = current.coefficient;
                tempHolder = tempHolder.times(tempHolder2);
                current = current.successor; //Moves to next one
                result = result.plus(tempHolder); //adds the values?
                tempHolder = new Polynomial(0.0,0); //resets it for next use                                
            }    
            return result;

        }

    final public int degree() 
    {
        return this.power; //THIS METHOD WAS GIVEN TO US!
    }
 //METHOD DONE BY Mitchell Bowie
    final public Polynomial differentiate() 
 {
    Polynomial result = new Polynomial (0.0,0); //The result polynomial
    Polynomial polynomial = this; //THIS polynomial. current one being assessed.
    if (polynomial.power==0)
    {           
        result.coefficient = (0.0); //returns 0.0 if its power = 0
        return result;
    }

     Polynomial temp = new Polynomial (0.0,0); // just a polynomial used to add things up

     while (polynomial != null) //goes through the polynomial
     {
        temp.coefficient = (polynomial.power*(polynomial.coefficient));
        temp.power = (polynomial.power -1);
        add (result, temp.coefficient, temp.power);                //adds the new values to a polynomial
        polynomial = polynomial.successor; //increments the polynomial //named result                
     } 
        return result; //returns the value added in the while loop

}


    final public Polynomial[] dividedBy(Polynomial that)
    {


        //THIS METHOD WAS TOO HARD!!!!! 
        Polynomial[] polynomials={that};
        return polynomials;
    }




    final public boolean equals(Polynomial that)
    {
        if (that == null) {
            return false;
        }

        if (this.coefficient != that.coefficient) {
            return false;
        }

        if (this.power != that.power) {
            return false;
        }

        if (this.successor == null && that.successor == null) { //THIS METHOD WAS GIVEN TO US!
            return true;
        }

        if (this.successor == null && that.successor != null) {
            return false;
        }

        if (this.successor != null && that.successor == null) {
            return false;
        }

        return this.successor.equals(that.successor);
    }

    //Method done by Mitchell
    final public double evaluate(double variable) 
    {        
        if (Double.isNaN(variable)) { //THIS IS ALL GIVEN
            variable = 0.0;
        }
        if (Math.abs(variable) < epsilon) {
            variable = 0.0;
        }
        double value = 0.0;

       //END OF GIVEN STUFF


        Polynomial current = this.clone(); //creates a copy of this

        while(current !=null) //goes through the copy until null
        {

            if(current.power > 0) //checks if power > 0
            {                
                value += current.coefficient * Math.pow(variable, current.power);
            }

            else //if its not then it will do this! 
            {

                value += current.coefficient; //adds the coefficient
            }

            current = current.successor; //iterates the loop
        }



            return value;// returns the value
    }
 //Method done by Mitchell and Callum
    final public Polynomial integrate() 
    {        
        if (this.coefficient == 0.0) 
        {
            return new Polynomial(0.0, 0); //Given part
        }
        Polynomial result = this.clone(); //why it was called result i dont know but this threw me
                                          //for a long time. -.-
        // End of given stuff


        Polynomial result2 = new Polynomial(0.0, 0);

        Polynomial tempHolder = new Polynomial(0.0, 0); //just holds temp values

        while(result!=null)
        {          
            tempHolder.coefficient = result.coefficient / (result.power +1);
            tempHolder.power = result.power + 1; //adds 1 to the power of result and sets it to 
                                                 //tempHolder
            result2 = result2.plus(tempHolder);
            result = result.successor; //iterates the loop
        }
        return result2; //returns result2 NOT result -.-
    }


    final public Polynomial minus(Polynomial that) 
    {
        if (that == null) {
            return null;
        }

        if (this.equals(that)) {
            return new Polynomial(0.0, 0);
        }

        Polynomial result = this.clone(); //THIS METHOD WAS GIVEN

        if (that.coefficient == 0.0) {
            return result;
        }

        Polynomial traverser = that;

        do {
            add(result, -traverser.coefficient, traverser.power);
            traverser = traverser.successor;
        } while (traverser != null);

        return result;
    }
    final public Polynomial plus(Polynomial that) 
    {
        if (that == null) {
            return null;
        }

        if (this.coefficient == 0.0) {
            return that.clone();
        }

        Polynomial result = this.clone(); //THIS METHOD WAS GIVEN TO US!

        if (that.coefficient == 0.0) {
            return result;
        }

        Polynomial traverser = that;

        do {
            add(result, traverser.coefficient, traverser.power);
            traverser = traverser.successor;
        } while (traverser != null);

        return result;
    }

    final public int powerMax()
    {
        int max = Integer.MIN_VALUE;

        Polynomial traverser = this;

        do {
            if (max < traverser.power) { //THIS METHOD WAS GIVEN TO US!
                max = traverser.power;
            } 
            traverser = traverser.successor; 
        } while (traverser != null); 
        return max;
    }

    final public int powerMin()
    {
        int min = Integer.MAX_VALUE;

        Polynomial traverser = this;

        do {
            if (min > traverser.power) {     //THIS METHOD WAS GIVEN TO US!
                min = traverser.power;
            }
            traverser = traverser.successor;
        } while (traverser != null);

        return min;
    }
//TIMES METHOD BY Callum
//Take current polynomial and times it by that polynomial.
//Uses dual while loops to get the results needed.
    final public Polynomial times(Polynomial that) 
    {

Polynomial result = new Polynomial (0.0,0);
Polynomial thiss = this;
int count = 0;
if (that == null)return null;
Polynomial newThat = that.clone(); //creates a clone of that
int length = that.cardinality();

if (thiss.coefficient == 0.0)
{
return result; //if this coefficient is 0.0 return 0.0
}
if (that.coefficient == 0.0)
{
return result; //if that coefficient is 0.0 return 0.0
}
while (thiss != null) //goes through thiss until its null
{
    double thissc = thiss.coefficient; //sets the double to the coefficient
    int thissp = thiss.power;          //sets the int to the power
    while (that !=null) //goes through that until null
    {        
        double thatc = that.coefficient; //sets the double to that coefficient
        int thatp = that.power; //sets the int to that power
        double resultc = thissc*thatc; // sets the result double to this coeff times that coeff
        int resultp = thissp+thatp; // sets the result int to this power plus that power
        if (count == 0) //if its the first value in the result it will just override the values
        {
            result.coefficient = resultc; //sets the coeff
            result.power = resultp; //sets the power
        }
        else
        {
        add(result,resultc, resultp); //adds the values to the result polynomial with add method        
        }
        count++; //count increase so it doesnt over ride the values
        that = that.successor; //iterates the inner loop!
    } 
    that = newThat;    //resets that to the start for next loop iteration! 
    thiss = thiss.successor; //iterates the loop!

} 
return result; //returns what is in result!
}

    final public String toString()
    {
        String string = "" + this.coefficient + (this.power == 0 ? "" : "*X^" + this.power);

        Polynomial traverser = this.successor;

        while (traverser != null) {
            string += (traverser.coefficient > 0.0 ? "+" : "") //THIS METHOD WAS GIVENT TO US!
                    + traverser.coefficient
                    + (traverser.power == 0 ? "" : "*X^"
                    + traverser.power);
            traverser = traverser.successor;
        }

        return string;
    }

}

1 Ответ

0 голосов
/ 28 мая 2011

Я бы начал с монома:

package poly;

public class Monomial
{
    private final double coeff;
    private final int expon;

    public Monomial()
    {
        this(0.0, 0);
    }

    public Monomial(double coeff)
    {
        this(coeff, 0);
    }

    public Monomial(double coeff, int expon)
    {
        this.coeff = coeff;
        this.expon = expon;
    }

    public double getCoeff()
    {
        return coeff;
    }

    public int getExpon()
    {
        return expon;
    }

    public Monomial add(Monomial other)
    {
        if (this.expon != other.expon)
            throw new IllegalArgumentException("Exponents must match in order to add");

        return new Monomial((this.coeff+other.coeff), this.expon);
    }

    public Monomial sub(Monomial other)
    {
        if (this.expon != other.expon)
            throw new IllegalArgumentException("Exponents must match in order to subtract");

        return new Monomial((this.coeff-other.coeff), this.expon);
    }

    public Monomial mul(Monomial other)
    {
        return new Monomial((this.coeff*other.coeff), (this.expon+other.expon));
    }

    public Monomial div(Monomial other)
    {
        return new Monomial((this.coeff/other.coeff), (this.expon-other.expon));
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o)
        {
            return true;
        }
        if (o == null || getClass() != o.getClass())
        {
            return false;
        }

        Monomial monomial = (Monomial) o;

        if (Double.compare(monomial.coeff, coeff) != 0)
        {
            return false;
        }
        if (expon != monomial.expon)
        {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode()
    {
        int result;
        long temp;
        temp = coeff != +0.0d ? Double.doubleToLongBits(coeff) : 0L;
        result = (int) (temp ^ (temp >>> 32));
        result = 31 * result + expon;
        return result;
    }

    @Override
    public String toString()
    {
        final StringBuilder sb = new StringBuilder();
        if (coeff != 1.0) sb.append(coeff);
        if (expon != 0) {
            sb.append('x');
            if (expon != 1) sb.append('^').append(expon);
        }
        return sb.toString();
    }
}

И юнит-тест, конечно же:

package poly;

import org.junit.Assert;
import org.junit.Test;

public class MonomialTest
{

    private static final double DELTA = 0.001;

    @Test
    public void testConstructor_Default()
    {
        Monomial test = new Monomial();
        Assert.assertEquals("0.0", test.toString());
    }

    @Test
    public void testConstructor_Constant()
    {
        Monomial test = new Monomial(2);
        Assert.assertEquals("2.0", test.toString());
    }

    @Test
    public void testConstructor()
    {
        Monomial test = new Monomial(6, 3);
        Assert.assertEquals("6.0x^3", test.toString());
        Assert.assertEquals(6.0, test.getCoeff(), DELTA);
        Assert.assertEquals(3, test.getExpon());
    }

    @Test
    public void testAddSuccess()
    {
        Monomial x = new Monomial(2, 3);
        Monomial y = new Monomial(3, 3);
        Monomial expected = new Monomial(5, 3);
        Assert.assertEquals(expected, x.add(y));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testAdd_MismatchedExponents()
    {
        Monomial x = new Monomial(2, 3);
        Monomial y = new Monomial(3, 4);
        x.add(y);
    }

    @Test
    public void testSubSuccess()
    {
        Monomial x = new Monomial(2, 3);
        Monomial y = new Monomial(3, 3);
        Monomial expected = new Monomial(-1, 3);
        Assert.assertEquals(expected, x.sub(y));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testSub_MismatchedExponents()
    {
        Monomial x = new Monomial(2, 3);
        Monomial y = new Monomial(3, 4);
        x.sub(y);
    }

    @Test
    public void testMulSuccess()
    {
        Monomial x = new Monomial(2, 3);
        Monomial y = new Monomial(3, 3);
        Monomial expected = new Monomial(6, 6);
        Assert.assertEquals(expected, x.mul(y));
    }

    @Test
    public void testDivSuccess()
    {
        Monomial x = new Monomial(4, 4);
        Monomial y = new Monomial(2, 3);
        Monomial expected = new Monomial(2, 1);
        Assert.assertEquals(expected, x.div(y));
    }

    @Test
    public void testEquals_null()
    {
        Monomial x = new Monomial();
        Assert.assertFalse(x.equals(null));
    }

    @Test
    public void testEquals_reflexive()
    {
        Monomial x = new Monomial(2, 3);
        Assert.assertTrue(x.equals(x));
    }

    @Test
    public void testEquals_symmetric()
    {
        Monomial x = new Monomial(2, 3);
        Monomial y = new Monomial(2, 3);
        Assert.assertTrue(x.equals(y) && y.equals(x));
        Assert.assertEquals(x.hashCode(), y.hashCode());
    }

    @Test
    public void testEquals_transitive()
    {
        Monomial x = new Monomial(2, 3);
        Monomial y = new Monomial(2, 3);
        Monomial z = new Monomial(2, 3);
        Assert.assertTrue(x.equals(y) && y.equals(z) && z.equals(x));
        Assert.assertEquals(x.hashCode(), y.hashCode());
        Assert.assertEquals(y.hashCode(), z.hashCode());
        Assert.assertEquals(z.hashCode(), x.hashCode());
    }

    @Test
    public void testEquals_differentCoefficients()
    {
        Monomial x = new Monomial(2, 3);
        Monomial y = new Monomial(3, 3);
        Assert.assertFalse(x.equals(y));
        Assert.assertFalse(x.hashCode() == y.hashCode());
    }


    @Test
    public void testEquals_differentExponents()
    {
        Monomial x = new Monomial(2, 3);
        Monomial y = new Monomial(2, 4);
        Assert.assertFalse(x.equals(y));
        Assert.assertFalse(x.hashCode() == y.hashCode());
    }
}

Тогда я бы написал полином, в котором List<Monomial> был бы закрытым элементом данных.

Возможно, вам нужен общий интерфейс для двух, так как вы сказали Composite. Но это только начало.

...