Skip to content

Instantly share code, notes, and snippets.

@RussellAndrewEdson
Created March 9, 2015 01:09
Show Gist options
  • Save RussellAndrewEdson/41e29e6329fb5c112f5a to your computer and use it in GitHub Desktop.
Save RussellAndrewEdson/41e29e6329fb5c112f5a to your computer and use it in GitHub Desktop.
Computes a polynomial using Horner's Rule.
public class HornersRule {
public static int totalAdditions = 0;
public static int totalMultiplications = 0;
/**
* Computes the value of the polynomial with the given coefficients
* at the point x, using Horner's Rule.
*
* @param coefficients An array of coefficients: a_i = coefficients[i]
* @param x The value at which to evaluate the polynomial.
* @return The value of the polynomial at the point x.
*/
public static double computePolynomial(double[] coefficients, double x) {
int n = coefficients.length - 1;
double result = coefficients[n];
for (int i = n-1; i >= 0; i--) {
result = (result * x) + coefficients[i];
totalAdditions += 1;
totalMultiplications += 1;
}
return result;
}
public static void main(String[] args) {
double[] examplePoly = new double[]{ -7, 1, -3, 2, 5 };
System.out.println("Polynomial: 5x^4 + 2x^3 - 3x^2 + x - 7");
System.out.print("x=3: ");
System.out.println(HornersRule.computePolynomial(examplePoly, 3));
System.out.print("Total additions: ");
System.out.println(HornersRule.totalAdditions);
System.out.print("Total multiplications: ");
System.out.println(HornersRule.totalMultiplications);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment