Hello I need help in this question
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Manav Divekar
le 4 Nov 2021
Commenté : Manav Divekar
le 4 Nov 2021
function [out] = sqrt_bywhile(x, inc)
sqrt = 0;
if ~exist('inc','var')
inc = 0.01;
end
inc1 = 0;
while sqrt <= x
sqrt = x^inc1;
inc1 = inc1+inc;
end
out = inc1-inc;
I am new to the matlab and working on while loops
I need to know how can I write a code for this.
Write a function sqrt_bywhile(x, inc) that estimates the square root of a number x. Start with an estimate of zero and gradually increase your estimate by inc at each step. Return an estimate whose square is equal to or less than x. Your estimate should be equal to the correct square root if the estimate can land on the correct value with the given inc (e.g., sqrt_bywhile(25,1) should return 5). Your estimate should be smaller than then correct square root if the estimate does not land on the correct value (e.g., sqrt_bywhile(24,1) should return 4 and sqrt_bywhile(26,1) should return 5). If inc is not given, use inc=0.01.
- You must use a while loop to solve this problem.
- Do not use for loops.
- Do not use vectorized code.
- Do not use the actual sqrt() function
0 commentaires
Réponse acceptée
Image Analyst
le 4 Nov 2021
Modifié(e) : Image Analyst
le 4 Nov 2021
Hint:
function sr = sqrt_bywhile(varargin)
x = varargin{1};
if length(varargin) > ...........
% code to get inc.
end
sr = 0; % Estimate of square root
while sr^2 < x
% code
end
I can't give you the full solution or you'd get in trouble for handing in my solution as your own.
2 commentaires
Image Analyst
le 4 Nov 2021
In your new, edited question where you give your code, don't use sqrt as a variable name since it's the name of the sqrt function. Choose a different name for that variable.
And I'm not sure why you're raising sqrt to the inc1 power. The power should always be 2. You should be incrementing your estimate, the badly-named sqrt, not the power.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!