<html>
<head>
<title>Método de Newton</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#CCCCCC" text="#000000">
<?
/*
Método de Newton em PHP versão 0.1
Código escrito por Laudelino ([email protected])
*/
function funcao($x) {
$fx = pow($x,2) + 2*$x - 3;
// outros exemplos (funções)
// $fx = 2*pow($x,3) + log($x) - 5; // Exemplo 1- f(x) = 2*x^3 + ln(x) - 5
// $fx = pow($x,2) - $x -2; // Exemplo 2- (x-2)(x+1) = x^2 -x -2 = f(x)
return $fx;
}
function derivada($x) {
$flinhax = 2*$x + 2;
// $flinhax = 6*pow($x,2) + 1/$x; // Exemplo 1- f'(x) = 6*x^2 + 1/x
// $flinhax = (2*$x) -1; // Exemplo 2- 2*x -1 = f'(x)
return $flinhax;
}
function metodo_de_newton($x) {
$funcao = funcao($x);
$derivada = derivada($x);
$xi_mais_1 = $x - $funcao/$derivada;
// Este é o algoritmo!
return $xi_mais_1;
}
$L = 10;
// Número máximo de repetições
$i = 0;
// Valor da primeira repetição (poderia ser 1 também)
$xi = array();
// Valores da seqüência
$xi[0] = 8;
// 1o. valor da seqüência, o ponto de partida, o valor inicial
echo "<table align=\"center\" border=\"1\">\n";
echo "<tr bgcolor=\"999999\"><td align=\"center\">n</td><td align=\"center\">x<sub>n</sub></td><td align=\"center\">f(x<sub>n</sub>)</td><td align=\"center\">f'(x<sub>n</sub>)</td><td align=\"center\">ERRO</td></tr>\n";
echo "<tr><td>0</td><td>" . $xi[0] . "</td><td>" . funcao($xi[0]) . "</td><td>" . derivada($xi[0]) . "</td><td align=\"center\">****</td></tr>\n";
while ($i < $L) {
if (derivada($xi[$i]) == 0 || funcao($xi[$i]) == 0) { $i = $L + 1; }
else {
$xi[$i+1] = metodo_de_newton($xi[$i]);
$erro = abs($xi[$i+1] - $xi[$i]);
echo "<tr><td>";
echo $i+1;
echo "</td><td>" . $xi[$i+1] . "</td><td>" . funcao($xi[$i+1]) . "</td><td>" . derivada($xi[$i+1]) . "</td><td>$erro</td></tr>\n";
$i = $i + 1;
}
}
echo "</table>";
?>
</body>
</html>