Hi,
I have a if-else-structure which exceeds the given limit, and I can't find out why. The code is:
recognition =0;
if recognition == 1
if weighted_timetable(quarter_of_the_day, activity_index, day_number) < 2
weighted_timetable(quarter_of_the_day, activity_index, day_number) = weighted_timetable(quarter_of_the_day, activity_index, day_number) + 0.1;
end
end
if recognition == 0
if weighted_timetable(quarter_of_the_day, activity_index, day_number) > 0.5
weighted_timetable(quarter_of_the_day, activity_index, day_number) = weighted_timetable(quarter_of_the_day, activity_index, day_number) - 0.1;
end
end
For recognition = 1, the code behaves as it should - it stops increasing the 3-D-Matrix at the given indexes when the value reaches 2. The problem lies in the second part: for recognition = 0, it decreases the value at the given indexes to 0.4, which means that it ignores the "> 0.5" limit, which I set.
After initializing all the needed variables, I ran only the code I posted with the "Evaluate Section" function to exclude any other factors, but the problem still persisted.
Thanks a lot for your help!
Cheers, Mathias

 채택된 답변

dpb
dpb 2016년 11월 23일
편집: dpb 2016년 11월 24일

0 개 추천

Welcome to the wild and wacky world of floating point arithmetic! 0.1 isn't exactly representable in binary (it's a continuing fraction, just as 1/3 is in decimal base 10) so the loop continues until the condition you've asked for is met--namely that the decrement continues until the value tested is <=0.5. You don't give the initial value for the beginning of the test, but for at least the cases you've observed the value less some number of 0.1 subtractions nearest 0.5 is just a tad over; hence it does another and results in a value about 0.4.
You'll need to add a tolerance on the test instead if you wish to terminate the loop at or near 0.5. See the eps function to get a value of roughly machine precision near the value that would be a good starting point.
if weighted_timetable(quarter_of_the_day, activity_index, day_number) > 0.5+2*eps(0.5)
would be a reasonable fixup or use a percentage if that's more natural.

댓글 수: 2

Hi and thanks for the answer! I've changed your input to
0.5+eps(0.5)
and it works now. The values in the matrix i'm working with are supposed to be in the range from 2 to 0.5. The initial value is 1, but that's just for the initialization of the matrix.
I guess i'll just have to live with this wacky stuff an find a more elegant solution.
Thanks again!
dpb
dpb 2016년 11월 24일
If you're going to use floating point arithmetic at all, yes, you'll "just have to live with it". See FAQ <Why 0.3 - 0.2 - 0.1 not zero?>
Please ACCEPT answer if this solves problem to indicate to others is closed if nothing else...

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

추가 답변 (0개)

질문:

2016년 11월 23일

댓글:

dpb
2016년 11월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by