IF statement if == "A variable" not working

조회 수: 3 (최근 30일)
Shasha Dra
Shasha Dra 2024년 4월 15일
댓글: Stephen23 2024년 4월 15일
Trying to do a heat conduction simulation my and my IF statement not working
I have a variable called 'b' which equal to 'maximum timestep - 1' and I want to use and IF to record maximum temperature
The IF statement not working when I use IF == b, but works with IF = 9999
  댓글 수: 1
Stephen23
Stephen23 2024년 4월 15일
"IF statement if == "A variable" not working"
IF statement is working: you are comparing two different values, ergo EQ returns FALSE. You need to learn how to work with binary floating point numbers. For example, either ROUND the result or compare the absolute difference against a tolerance:
abs(A-B)<tol
This is a completely expected result with binary floating point numbers:
This is worth reading as well:
and also a brief overview of the topic:

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

답변 (2개)

Fangjun Jiang
Fangjun Jiang 2024년 4월 15일
편집: Fangjun Jiang 2024년 4월 15일
Most likely it is a floating point data equal comparison problem. b is somewhere near 9999 but not exactly. Use round() or integer data type.
a=1-1/3
a = 0.6667
b=2/3
b = 0.6667
a==b
ans = logical
0

Voss
Voss 2024년 4월 15일
"The IF statement not working when I use IF == b, but works with IF = 99999"
The behavior is not the same when using b vs when using 99999 because b is not exactly equal to 99999.
format long g
T= 1; %simulation time seconds
del_t= 1E-5; %time step size
N = T/del_t %Number of time discretization
N =
100000
b=(T/del_t)-1 % N-1
b =
99999
b looks like it is equal to 99999, but it's not.
b == 99999 % nope
ans = logical
0
It's actually slightly smaller:
fprintf('%.40f',b)
99998.9999999999854480847716331481933593750000
Consider the behavior of the following two loops:
counter = 1;
counter_hit_b = false;
while counter < N
counter = counter+1;
if counter == b
counter_hit_b = true;
end
end
disp(counter_hit_b)
0
counter = 1;
counter_hit_99999 = false;
while counter < N
counter = counter+1;
if counter == 99999
counter_hit_99999 = true;
end
end
counter_hit_99999
counter_hit_99999 = logical
1
The counter is 99999 at some point, but it is never b.
To get the right behavior using b instead of hard-coding 99999, you can define b to be exactly 99999 by using round.
b = round(T/del_t-1)
b =
99999
fprintf('%.40f',b)
99999.0000000000000000000000000000000000000000
b == 99999 % now b is exactly 99999
ans = logical
1

카테고리

Help CenterFile Exchange에서 General Applications에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by