En route from Ottawa to Montreal, I spent about 20 minutes working on a Java assignment. Usually these assignments are quite boring, and this one was no exception. The basic assignment is to create a class that represents a single variable polynomial of given degree. Anyways, the polynomial needed a function to evaluate it for a given value, and eventually I coded up this:
private double evalCoeff(int deg, double x)
{
if (deg == this.getDegree())
return this.coefficients[deg];
return evalCoeff(deg + 1, x) * x + this.coefficients[deg];
}
/**
* Evaluate the polynomial for a given x value.
*
* @param x The value.
* @returns The evaulated value.
*/
public double evaluate(double x)
{
// Very, very slick.
return evalCoeff(0, x);
}
Isn’t that beautiful recursiveness?
This could be optimized by checking if x == 0 and returning this.coefficients[0] if so.
Comment by Anonymous — 2010/03/12 @ 4:40 pm
Yes, very pretty.
Comment by Anonymous — 2010/03/12 @ 4:40 pm