Lewis Lewis - 4 years ago 259
HTML Question

Newton Raphson method JavaScript

I try to do a Newton Raphson method with JS.
I did that code but, on this code the polinomy it's defined and I need to pass manually.
I don't know how I can put a polinomy manually. Please any idea... :(

<script language="javascript">
function funcion(x)
return Math.cos(x) - x * x * x;
function derivada(x)
return -Math.sin(x) - 3.0 * x * x * x;
function procesar(formulario)
var i = 0;
var err, x_1, x = parseFloat(formulario.x.value);
var resultado = '<table border="1"><thead><tr><td align="center">i</td><td align="center">x<sub></sub></td><td align="center">error</td></tr></thead><tbody>';
x_1 = x;
x = x - funcion(x) / derivada(x);
err = Math.abs((x - x_1) / x);
resultado += '<tr><td>x<sub>' + i + '</sub></td><td>' + x_1 + '</td><td>' + err + '</td></tr>';
} while (x != x_1 && i < 100);
document.getElementById('resultado').innerHTML = resultado + '</tbody></table><br>' + (i == 100 ? 'La solucion no es convergente. ' : 'La solucion es ' + x);
return false;

That's my html:

<h1 align="center">Metodo de Newton-Raphson</h1>

<form name="formulario" onsubmit="return procesar(this);">
Ingrese la función
<input name="x" type="text" size="4" />
<input type="submit" value="Procesar" />

<table align="center" bgcolor="white">

<div id="resultado"></div>


Answer Source

You need to add a new input and take in the function as a string. then pass that function to your funcion function and use eval() to evaluate it after replacing all occurences of x with the value the user entered.

Change your form to this:

<form name="formulario" onsubmit="return procesar(this);">
    Ingrese el valor
    <input name="x" type="text" size="4" />
    Ingrese la función
    <input name="func" type="text" size="15" />
    <input type="submit" value="Procesar" />

and then change your funcion function to:

function funcion(func,x) {
  var newFunc = func.replace(/x/g,x);
  return eval(newFunc);

also add:

var func = document.getElementsByName("func")[0].value;

to handle the new input, and pass it as function(func,x) when you calculate your result

The last step is to calculate the derivative of the function your user entered. I suggest using a library like this one to do the work.

see a live example (minus derivative) here: http://codepen.io/anon/pen/pgEdGW

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download