making sqrt file without using sqrt function

댓글 수: 4

Sam Chak
Sam Chak 2023년 4월 9일
This looks like some kind of a puzzle. If one is not good at math, are they allowed to bend the rules cleverly (without using sqrt() and ^(1/2))? Need more info.
DGM
DGM 2023년 4월 9일
편집: DGM 2023년 4월 9일
For scalar inputs, I suppose you could always just do it with fzero() or fsolve().
imnotclever(25)
ans = 5
imnotclever(-16)
ans = 0.0000 + 4.0000i
imnotclever(37)
ans = 6.0828
function out = imnotclever(x)
xsign = sign(x);
x = abs(x);
f = @(y) y^2 - x;
out = fzero(f,x);
if xsign < 0
out = 1i*out;
end
end
Then again, if they want to teach numerical methods, why would they let you use fzero() either?
I'm sure someone has a more elegant way to do it, but I'm not feeling particularly clever.
How about the Bisection method?
This sounds like a homework assignment. If it is, show us the code you've written to try to solve the problem and ask a specific question about where you're having difficulty and we may be able to provide some guidance.
If you aren't sure where to start because you're not familiar with how to write MATLAB code, I suggest you start with the free MATLAB Onramp tutorial to quickly learn the essentials of MATLAB.
If you aren't sure where to start because you're not familiar with the mathematics you'll need to solve the problem, I recommend asking your professor and/or teaching assistant for help.

댓글을 달려면 로그인하십시오.

답변 (2개)

Walter Roberson
Walter Roberson 2023년 4월 10일

0 개 추천

Each step iteration improves the precision, so with 9 digits as the target precision, you can take 9 iterations.
Sam Chak
Sam Chak 2023년 4월 10일
편집: Sam Chak 2023년 4월 10일
Hi @zot
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)
x =
10.0498756211209
err =
0
xx = 1×7
5 12.6 10.3079365079365 10.0531059195057 10.0498761401062 10.0498756211209 10.0498756211209

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

태그

질문:

zot
2023년 4월 9일

편집:

2023년 4월 10일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by