making sqrt file without using sqrt function
1 visualizzazione (ultimi 30 giorni)
Walter Roberson il 10 Apr 2023
You can code Hero's Method; see https://blogs.sas.com/content/iml/2016/05/16/babylonian-square-roots.html
Each step iteration improves the precision, so with 9 digits as the target precision, you can take 9 iterations.
Sam Chak il 10 Apr 2023
Modificato: Sam Chak il 10 Apr 2023
Edit: Since you didn't provide more info, then I'd suggest Newton–Raphson method.
From the definition
it can be rearranged to
to repeat the iteration until the required accuracy is achieved. You can modify Newton–Raphson code for calculating the square root of a real number. Also, address the situations when the initial guess is very far from the real solution (usually happens for very large real number).
The code should generate result like this:
format long g
fun = inline('x^2 - 101', 'x');
x0 = 5; % initial guess
TolX = 1e-9;
[x, err, xx] = modNRsqrt(fun, x0, TolX)