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

To find the zeros of a polynomial, we can use the Newton-Raphson method in combination with the Polynomial class provided by the math.js library. Here is the code to do so:

First, we will include the math.js library in our html file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.3.2/math.min.js"></script>
88 chars
2 lines

Then, in our javascript file, we can write the following code:

index.tsx
//parse the input polynomial
let polyString = prompt("Enter a polynomial function in x: ");
let polynomial = math.parse(polyString).compile();

//define the function to find the zeros of
let f = function(x) {
  return polynomial.evaluate({x: x});
}

//define the derivative of the polynomial
let df = function(x) {
  let dPolynomial = math.derivative(polyString, 'x');
  let result = dPolynomial.evaluate({x: x});
  return result;
}

//define the Newton-Raphson method
let newtonRaphson = function(x0, tol, maxIter) {
  let x = x0;
  let fx = f(x);
  let dfx = df(x);
  let iter = 0;
  while (Math.abs(fx) > tol && iter < maxIter) {
    x = x - (fx / dfx);
    fx = f(x);
    dfx = df(x);
    iter += 1;
  }
  if (iter === maxIter) {
    console.error('newtonRaphson did not converge');
  }
  return x;
}

//find the zeros
let zeros = [];
let x0 = -10;
let tol = 1e-6;
let maxIter = 100;
while (true) {
  let zero = newtonRaphson(x0, tol, maxIter);
  if (Number.isNaN(zero)) {
    break;
  }
  zeros.push(zero);
  x0 = zero + 1;
}

//print the zeros to the console
console.log(`The zeros of ${polyString} are: ${zeros}`);
1122 chars
51 lines

In this code, we first prompt the user to enter a polynomial formula, parse it using math.js, and compile it into a function that can be evaluated at any value of x. We then define the mathematical functions we need, including the f(x) and df(x)/dx functions for the Newton-Raphson method. Finally, we iterate over the possible zeros, using the Newton-Raphson method to find each zero, and adding it to our list of zeros until we have found them all.

Note that this code assumes that there are no repeated roots and that the polynomial has real roots. The method used also assumes that the initial guess is close enough to the actual root. If these assumptions are not true, the code may not converge or may not return all the zeros of the polynomial.

gistlibby LogSnag