Search code examples
javacalculus

How do I pass in a polynomial function in java?


For a programming project in Calculus we were instructed to code a program that models the Simpson's 1/3 and 3/8 rule.

We are supposed to take in a polynomial(i.e. 5x^2+7x+10) but I am struggling conceptualizing this. I have began by using scanner but is there a better way to correctly read the polynomial?

Any examples or reference materials will be greatly appreciated.


Solution

  • I'd suggest that you start with a Function interface that takes in a number of input values and returns an output value:

    public interface Function {
        double evaluate(double x);
    }
    

    Write a polynomial implementation:

    public class Poly {
    
        public static double evaluate(double x, double [] coeffs) {
            double value = 0.0;
            if (coeffs != null) {
                // Use Horner's method to evaluate.
                for (int i = coeffs.length-1; i >= 0; --i) {
                    value = coeffs[i] + (x*value);
                }
            }
            return value;
        }
    }
    

    Pass that to your integrator and let it do its thing.