Question #63618

Make a javascript code for horner's rule polynomial evaluation
1

Expert's answer

2016-11-25T07:58:10-0500

Answer on Question #63618, Programming & Computer Science | JavaScript

Question:

Make a javascript code for Horner's rule polynomial evaluation

Solution:

function horner(coeffs, x) {
    return coeffs.reduce( // Reduce means apply function (that passed as first argument) to the array from left to right
        function (acc, coeff) { return (acc * x + coeff) },
        0); // Initial value == 0
}
// evaluate polynomial at x=3
var x = 3;
// -19*x^7 + 17*x^6 - 13*x^5 + 11*x^4 - 7*x^3 + 5*x^2 - 3*x^1 + 2*x^0
var coeff = [-19, 17, -13, 11, -7, 5, -3, 2]
// Evaluate and print result
console.log(horner(coeff, x)); // ==> -31579

Example test RUN within HTML page:

<!DOCTYPE  > <head>
<head>
<title>Horner rule</title>
<script></script>
function horner(coeffs, x) {
    return coeffs.reduce( // Reduce means apply function (that passed as first argument) to the array from left to right
        function(acc, coeff) { return(acc * x + coeff) },
        0); // Initial value == 0
}
// evaluate polynomial at x=3
var x = 3;
// -19*x^7 + 17*x^6 - 13*x^5 + 11*x^4 - 7*x^3 + 5*x^2 - 3*x^1 + 2*x^0
var coeff = [-19,17,-13,11,-7,5,-3,2]
// Evaluate and print result
console.log(horner(coeff, x)); // ==> -31579
function printPoly(coeff) {
    s = ''
    for(var i = 0; i < coeff.length; ++i) {
        if( coeff[i] == 0 ) continue;
        s += (coeff[i] > 0 ? "+" : "") + coeff[i] + "*x^" + (coeff.length - i - 1);
    }
    return s;
}
function run() {
    var coeff = prompt("Enter polynomial coefficients (from highest to lowest degree) separated by coma: ", "-19,17,-13,11,-7,5,-3,2").split(",")
    var x = prompt("Enter point at witch you want to evaluate your polynomial, x=", "3");
    for(var i = 0; i < coeff.length; ++i) {
        coeff[i] = parseInt(coeff[i], 10);
    }
    document.write("Your polynomial: " + printPoly(coeff) + "<br>");
    document.write("Your point x=" + x + "<br>");
    document.write("Evaluation result=" + horner(coeff, x) + "<br>");
}
</script>
</head>
<body onload="run();">
</body>
</head>


http://www.AssignmentExpert.com

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS