Last active
August 29, 2015 14:16
-
-
Save RussellAndrewEdson/442af82526b851f8a83b to your computer and use it in GitHub Desktop.
Computes a polynomial by caching intermediate powers of x.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Polynomial2 { | |
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 polynomial at the point x. | |
*/ | |
public static double computePolynomial(double[] coefficients, double x) { | |
int n = coefficients.length - 1; | |
/* This time, we'll assign the x^0 coefficient to result right away. */ | |
double result = coefficients[0]; | |
double powerOfX = 1.0; | |
for (int i = 1; i <= n; i++) { | |
powerOfX *= x; | |
result += coefficients[i] * powerOfX; | |
totalAdditions += 1; | |
totalMultiplications += 2; | |
} | |
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(Polynomial2.computePolynomial(examplePoly, 3)); | |
System.out.print("Total additions: "); | |
System.out.println(Polynomial2.totalAdditions); | |
System.out.print("Total multiplications: "); | |
System.out.println(Polynomial2.totalMultiplications); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment