I cannot for the life of me understand why this code isn’t working. I am creating a function to evaluate a polynomial at all of the points over a given x interval, at a frequency specified by the user. My underlying Polynomial code is irrelevent to the problem. My problem is filling my array with the values I am obtaining from Horner’s method.
public double[] evalAt(double s, double f, int n) {
double[] resultArray = new double[n];
double h =((f - s)/(n));
if(s==f) {
double tempResult = 0;
for (int i = this.degree; i >= 0; i--) {
tempResult = tempResult * s + this.terms[i].getCoefficient();
}
resultArray[0] = tempResult;
} else {
int counter = 0;
for(double i = s; i <= f; i=i+h) {
double tempResult = 0;
for (int j = this.degree; j >= 0; j--) {
tempResult = tempResult * i + this.terms[j].getCoefficient();
}
System.out.println("Counter: " + counter + " Result @ Counter: " + tempResult);
resultArray[counter++] = tempResult;
}
System.out.println(resultArray[0]);
System.out.println(resultArray[1]);
System.out.println(resultArray[2]);
System.out.println(resultArray[3]);
}
return resultArray;
}
I have a print statement in there to show me what the values of the counter and the temporary result are. then I use the resultArray['index'] = 'value'; syntax. When I run this, I see that the counter and the value are exactly as I want them, however when I check the array with the four print statements at the bottom, nothing happens. My inputs are 0,10,10:
Output:
Counter: 0 Result @ Counter: 0.0
Counter: 1 Result @ Counter: 1.0
Counter: 2 Result @ Counter: 4.0
Counter: 3 Result @ Counter: 9.0
Counter: 4 Result @ Counter: 16.0
Counter: 5 Result @ Counter: 25.0
Counter: 6 Result @ Counter: 36.0
Counter: 7 Result @ Counter: 49.0
Counter: 8 Result @ Counter: 64.0
Counter: 9 Result @ Counter: 81.0
Counter: 10 Result @ Counter: 100.0
I strongly suspect it is throwing an ArrayIndexOutOfBoundsException which is getting swallowed outside this method.
You are creating an array of size
n, in this case 10, but your counter goes from zero tof(also 10) which is a total of 11 elements. So there’s an off-by-one in at least one of those.Look through your code and find the bit that says
and change it to
to help catch this kind of error more easily.