Mathieu Fenniak's Weblog

2002/10/27

Recursiveness

Filed under: java,programming — admin @ 4:52 am

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? :)

2 Comments

  1. This could be optimized by checking if x == 0 and returning this.coefficients[0] if so.

    Comment by Anonymous — 2010/07/29 @ 5:26 am

  2. Yes, very pretty.

    Comment by Anonymous — 2010/07/29 @ 5:26 am

RSS feed for comments on this post. TrackBack URL

Sorry, the comment form is closed at this time.

Powered by WordPress