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

Here is a function written in JavaScript that returns the zeros of a polynomial formula entered by the user:

index.tsx
function findZeros() {
  // Get the polynomial formula from the user
  let poly = prompt("Enter the polynomial formula:");

  // Parse the formula into a function
  let polyFunction = new Function("x", "return " + poly);

  // Find the zeros using the Newton-Raphson method
  let x0 = 1.0;  // Starting value
  let tolerance = 1e-6;  // Desired accuracy
  let numIterations = 100;  // Maximum number of iterations
  let x = x0;
  let fx = polyFunction(x);
  let dx = 0.0;

  for (let i = 0; i < numIterations; i++) {
    let fpx = (polyFunction(x + tolerance) - fx) / tolerance;
    dx = -fx / fpx;
    x += dx;
    fx = polyFunction(x);

    if (Math.abs(dx) < tolerance && Math.abs(fx) < tolerance) {
      break;
    }
  }

  // Display the zeros to the user
  alert("The zeros of the polynomial are: " + x);
}
814 chars
30 lines

This function first prompts the user to enter the polynomial formula. It then parses the formula into a function using the Function constructor.

The function then uses the Newton-Raphson method to find the zeros of the polynomial. This method uses an iterative approach to converge on the zeros. The starting value is set to 1.0, the desired accuracy is set to 1e-6 (i.e. six decimal places), and the maximum number of iterations is set to 100.

Finally, the function displays the zeros to the user using alert(). Note that this function assumes that the polynomial formula entered by the user is valid and can be parsed into a function.

gistlibby LogSnag