Вот как я написал бы это на Java:
/**
* Polynomial
* User: Michael
* Date: Jul 27, 2010
* Time: 7:15:41 PM
*/
public class Polynomial
{
private double [] coeff;
public Polynomial(double[] coeff)
{
if ((coeff == null) || (coeff.length == 0))
throw new IllegalArgumentException("coefficient array cannot be null or empty");
this.coeff = new double [coeff.length];
System.arraycopy(coeff, 0, this.coeff, 0, coeff.length);
}
public double eval(double x)
{
int numTerms = coeff.length;
double value = coeff[numTerms-1];
for (int i = (numTerms-2); i >= 0; --i)
{
value += value*x + this.coeff[i];
}
return value;
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder(128);
for (int i = 0; i < (this.coeff.length-1); ++i)
{
builder.append("a[").append(i).append("]=").append(this.coeff[i]).append(",");
}
builder.append("a[").append(this.coeff.length-1).append("]=").append(this.coeff[this.coeff.length-1]);
return builder.toString();
}
}
Вот как я это проверю:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* PolynomialTest
* User: Michael
* Date: Jul 27, 2010
* Time: 7:26:15 PM
*/
public class PolynomialTest
{
private static final double [] a =
{
-4.2294409347240979E+01,
5.5946102161174718E+00,
-1.3446057748924720E-01,
1.5448461146899649E-03,
-8.2537158069276241E-06,
1.7176546321558128E-08,
};
private Polynomial p = new Polynomial(a);
@Test
public void testEval()
{
double x = 94.0;
double expected = 60.83781703621137;
double actual = p.eval(x);
assertEquals(expected, actual, 1.0e-3);
}
@Test
public void testToString()
{
String expected = "a[0]=-42.29440934724098,a[1]=5.594610216117472,a[2]=-0.1344605774892472,a[3]=0.0015448461146899649,a[4]=-8.253715806927624E-6,a[5]=1.7176546321558128E-8";
String actual = p.toString();
assertEquals(expected, actual);
}
}