# I need help with using a while loop

7 vues (au cours des 30 derniers jours)
Ikmal Rosli le 19 Avr 2021
Commenté : Ikmal Rosli le 19 Avr 2021
My problem I think is quite simple. But I just cannot get my brain around it.
I'm trying to use a while loop to iterate my code until m = 1.000e-5. But when I execute the code what I get is an infinite loop.
Here is the code:
c1 = 0.1;
v1 = 0.1;
v2 = 1;
p = 0;
m = 0;
while m ~= 1.000e-5
c1 = c1*v1/v2
m = c1*0.1
p = p+1
end
##### 0 commentairesAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Paul Hoffrichter le 19 Avr 2021
Modifié(e) : Paul Hoffrichter le 19 Avr 2021
Looks like you are trying to solve a difference equation. Take a look at what is happening:
c1 = 0.1;
v1 = 0.1;
v2 = 1;
p = 2;
m = 0;
while m ~= 1.000e-5
c1(p) = c1(p-1)*v1/v2; % ==> c1 = c1 * 0.1 since v1, v2 never change in loop
m(p-1) = c1(p)*0.1;
if p > 100 || m(p-1) < 1e-8
break;
end
p = p+1;
end
figure(1), plot(c1), title('c1'), xlim([1 15])
figure(2), plot(m), title('m'), xlim([1 15])
c1
m
Output:
c1 =
0.100000000000000 0.010000000000000 0.001000000000000 0.000100000000000 0.000010000000000 0.000001000000000 0.000000100000000 0.000000010000000
m =
1.0e-03 *
1.000000000000000 0.100000000000000 0.010000000000000 0.001000000000000 0.000100000000000 0.000010000000000 0.000001000000000
m is decreasing rapidly. Never compare real numbers for equality or inequality. Remove my if-break statement, and adjust your while-loop accordingly.
##### 1 commentaireAfficher AucuneMasquer Aucune
Ikmal Rosli le 19 Avr 2021
oh wow never thought of this. Thanks.

Connectez-vous pour commenter.

### Plus de réponses (1)

David Hill le 19 Avr 2021
c1 = 0.1;
v1 = 0.1;
v2 = 1;
p = 0;
m = 1;
while m > 1.000e-5%floating point errors, use >
c1 = c1*v1/v2
m = c1*0.1
p = p+1
end
##### 1 commentaireAfficher AucuneMasquer Aucune
Ikmal Rosli le 19 Avr 2021
Hello thank you. Is there a way to get around the floating point error. So that m is exactly equal to 1e-5

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by