The JavaScript code example demonstrates how to find a zero of a function using a fixed-point algorithm.
<!DOCTYPE html>
<html>
<head>
<title>XoaX.net's Javascript</title>
<style>
table {
background-color:white;
}
</style>
</head>
<body>
<script type="text/javascript" src="FindingAZeroWithAFixedPoint2.js"></script>
</body>
</html>FindZeroAtSqrt2();
function FindZeroAtSqrt2() {
let dX0 = 0.0;
let dX1 = 2.0;
document.writeln('<table cellspacing="5" cellpadding="5" border="3">');
document.writeln('<thead><tr><th>X0</th><th>X1</th></tr></thead>');
while (Math.abs(dX0 - dX1) > 1.0e-5) {
dX0 = dX1;
dX1 = FixedPoint(dX1);
document.writeln('<tr><td>'+dX0+'</td><td>'+dX1+'</td></tr>');
}
document.writeln('</table>');
}
// Given y = x^2-2
// To find y(x) = 0 or 0 = x^2-2, mulitplply by -.5 and add x to get x = 1 - .5x^2 + x.
// Now, sqrt(2) is a fixed point of y = 1 - .5x^2 + x
// Note that y'(sqrt(2)) = sqrt(2) - 1 < 1. So, the algorithm converges.
// Let x(n) = 1 - .5*(x(n-1)^2) + x(n-1)
function FixedPoint(dX) {
return 1 - .5*dX*dX + dX;
}
© 20072026 XoaX.net LLC. All rights reserved.