Multiply a polynomial by a constant in Java

I am having trouble multiplying the polynomial by a constant (double). It works when there is only one coefficient, but when there is more than one, it gives an ArrayIndexOutOfBounds error and points to the setCoefficient method. Any help? Thanks

public class Poly { private float[] coefficients; public Poly() { coefficients = new float[1]; coefficients[0] = 0; } public Poly(int degree) { coefficients = new float[degree+1]; for (int i = 0; i <= degree; i++) coefficients[i] = 0; } public Poly(float[] a) { coefficients = new float[a.length]; for (int i = 0; i < a.length; i++) coefficients[i] = a[i]; } public int getDegree() { return coefficients.length-1; } public float getCoefficient(int i) { return coefficients[i]; } public void setCoefficient(int i, float value) { coefficients[i] = value; } public Poly add(Poly p) { int n = getDegree(); int m = p.getDegree(); Poly result = new Poly(Poly.max(n, m)); int i; for (i = 0; i <= Poly.min(n, m); i++) result.setCoefficient(i, coefficients[i] + p.getCoefficient(i)); if (i <= n) { //we have to copy the remaining coefficients from this object for ( ; i <= n; i++) result.setCoefficient(i, coefficients[i]); } else { // we have to copy the remaining coefficients from p for ( ; i <= m; i++) result.setCoefficient(i, p.getCoefficient(i)); } return result; } public void displayPoly () { for (int i=0; i < coefficients.length; i++) System.out.print(" "+coefficients[i]); System.out.println(); } private static int max (int n, int m) { if (n > m) return n; return m; } private static int min (int n, int m) { if (n > m) return m; return n; } public Poly multiplyCon (double c){ int n = getDegree(); Poly results = new Poly(); // can work when multiplying only 1 coefficient for (int i =0; i <= coefficients.length-1; i++){ // errors ArrayIndexOutOfBounds for setCoefficient results.setCoefficient(i, (float)(coefficients[i] * c)); } return results; } } 
+6
source share
2 answers

Replace Poly results = new Poly(); on Poly results = new Poly(n); .

+4
source

I believe you should replace the multiplyCon method

 Poly results = new Poly(); 

from

 Poly results = new Poly(n); 

By default, the default constructor creates an array with only one coefficient, which explains why multiplication of the one-component polynomial works.

+4
source

Source: https://habr.com/ru/post/897642/


All Articles