Skip to content

Instantly share code, notes, and snippets.

@RussellAndrewEdson
Last active August 29, 2015 14:16
Show Gist options
  • Save RussellAndrewEdson/d85213ac830b2b0d7dae to your computer and use it in GitHub Desktop.
Save RussellAndrewEdson/d85213ac830b2b0d7dae to your computer and use it in GitHub Desktop.
Computes a polynomial in the obvious (less efficient) way.
public class Polynomial1 {
public static int totalAdditions = 0;
public static int totalMultiplications = 0;
/**
* Computes the value of the polynomial with the given coefficients
* at the point x.
*
* @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 poloynomial at the point x.
*/
public static double computePolynomial(double[] coefficients, double x) {
int n = coefficients.length - 1;
double result = 0.0;
for (int i = n; i >= 0; i--) {
result += coefficients[i] * Math.pow(x, i);
totalAdditions += 1;
totalMultiplications += i;
}
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(Polynomial1.computePolynomial(examplePoly, 3));
System.out.print("Total additions: ");
System.out.println(Polynomial1.totalAdditions);
System.out.print("Total multiplications: ");
System.out.println(Polynomial1.totalMultiplications);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment