Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass in a polynomial function in java?

Tags:

java

calculus

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.

like image 264
user2132947 Avatar asked Nov 23 '25 01:11

user2132947


1 Answers

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.

like image 74
duffymo Avatar answered Nov 24 '25 14:11

duffymo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!