Question

I need an enhancement on Brute-Force polynomial evaluation algorithm. I received the highest power of x (value of n), the value of coefficients of all elements of polynomial (a, b, c, ..) as an integer array list. But I can't apply this algorithm on java: f(x) = ax^n + bx^(n-1) + cx^(n-3)+... + z How can I apply this polynomial on java? What is the algorithm for it? Any helps?

package brute.force;

import java.util.*;
import java.util.Scanner;

public class BruteForce {

    public static void main(String[] args) {
        Scanner scan = new Scanner (System.in);
        ArrayList<Integer> coefficients = new ArrayList<>();
        int powerOfX, x;

        System.out.print("Enter integers please ");
        System.out.println("(EOF or non-integer to terminate): ");

        while(scan.hasNextInt()){
         coefficients.add(scan.nextInt());
        }

        Integer [] nums = coefficients.toArray(new Integer[0]);
        for(int i = 0; i < nums.length; i++){
            System.out.println(nums[i]);
        }
    }   
}
Was it helpful?

Solution

You need to calculate it with following iteration:

    double result = 0;
    Integer [] nums = coefficients.toArray(new Integer[0]);
    for(int i = 0; i < nums.length; i++){
        result = result *x + nums[i];
    }
    System.out.println(result);

It is known as Horner's method. The benefit of this approach for example of fourth degree of polynomial is:

f(x) = ax^3 + bx^2 + cx + z

is transformed to:

f(x) = ((a)*x + b)*x + c)*x + z

OTHER TIPS

You mean this?

double result = 0;
for(int i = 0; i < nums.length; i++) {
   result += nums[i] * Math.pow(x, i);  // nums has coefficients in increasing order
}

You can use Horner's method to calculate a polynomial in a computationally efficient form.

user987339 has posted an implementation in Java.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top