Filter löschen
Filter löschen

if within while loop not recognized

1 Ansicht (letzte 30 Tage)
Ramu Nair R
Ramu Nair R am 2 Apr. 2018
Bearbeitet: Ramu Nair R am 2 Apr. 2018
while(t<0.1)
if(t==0.05) v=3; end % NOT GETTING REFLECTED IN v
t=t+Ts;
end

Akzeptierte Antwort

Birdman
Birdman am 2 Apr. 2018
Bearbeitet: Birdman am 2 Apr. 2018
A trivial answer:
Use ismembertol for comparing values with tolerance
tol=1e-6;
if ismembertol(t,0.05,tol)

Weitere Antworten (1)

John D'Errico
John D'Errico am 2 Apr. 2018
NEVER test for exact equality of a floating point number.
Since doubles are stored in binary, remember that almost all decimal fractions cannot be represented exactly as a double, just like you cannot represent 1/3 exactly as a terminating decimal in a limited number of decimal digits. Doubles use 52 binary bits to store the mantissa, so that is your limit.
Instead, 0.05 is stored as the closest value possible. So never test for exact equality. Just use a tolerance.
if abs(t - 0.05) < 1e-16

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by