Here's a MATLAB code that uses the Newton-Raphson method to compute the square root of 5:
main.m387 chars17 lines
The code defines the function f(x) = x^2 - 5
and its derivative df(x) = 2x
. It starts with an initial guess of x0 = 2.5
, and iteratively applies the Newton-Raphson method until the change in x0
falls below the desired accuracy eps
. The resulting square root of 5 is printed with the disp
command.
Running this code in MATLAB will yield the result:
main.m17 chars2 lines
which is the correct value for the square root of 5.
gistlibby LogSnag