write a program that returns the zeros of a polynomial formula when the user enters it in javascript in python

Here's an implementation of finding zeros of a polynomial using the Newton-Raphson method in JavaScript:

index.tsx
// define the polynomial function
function f(x){
    return x*x - 4*x + 3;
}

// define the derivative of the polynomial function
function fprime(x){
    return 2*x - 4;
}

// define the Newton-Raphson method function
function newtonRaphson(x0, tol){
    var xn = x0;
    var xn1 = 0;
    var fxn;
    var fpxn;
    var diff = Math.abs(xn1 - xn);

    while (diff > tol){
        fxn = f(xn);
        fpxn = fprime(xn);
        xn1 = xn - fxn/fpxn;
        diff = Math.abs(xn1 - xn);
        xn = xn1;
    }

    return xn1;
}

// Usage
var root = newtonRaphson(1, 0.0001);
console.log("The root for the polynomial is: " + root.toFixed(4));
641 chars
33 lines

In Python, the implementation would look like this:

main.py
# define the polynomial function
def f(x):
    return x*x - 4*x + 3

# define the derivative of the polynomial function
def fprime(x):
    return 2*x - 4

# define the Newton-Raphson method function
def newtonRaphson(x0, tol):
    xn = x0
    xn1 = 0
    fxn = 0
    fpxn = 0
    diff = abs(xn1 - xn)

    while (diff > tol):
        fxn = f(xn)
        fpxn = fprime(xn)
        xn1 = xn - fxn/fpxn
        diff = abs(xn1 - xn)
        xn = xn1

    return xn1

# Usage
root = newtonRaphson(1, 0.0001)
print("The root for the polynomial is: {:.4f}".format(root))
564 chars
29 lines

Note that there are other numerical methods for finding zeros of polynomials, such as the bisection method or the Secant method.

gistlibby LogSnag