NaN for zero divide by zero.

조회 수: 4 (최근 30일)
Stian Molvik
Stian Molvik 2011년 4월 6일
Will illustrate with an example, I.e:
a = (0:0.1:1); b = (1-a)*2./(1-a);
Matlab will output the end value in b as NaN, when in reality b should converge to 2 for a = 1.
How can I avoid this?

채택된 답변

Matt Fig
Matt Fig 2011년 4월 6일
There are two things to remember when looking at this problem.
1. A function having a limit as the independent variable approaches a point does not imply that the function value at that point is defined. You plugged in for the function value at that point. The fact that you get NAN says nothing about the limit of the function as the independent variable approaches that point.
2. NAN is the correct value when evaluating the function at that point. This is a standard double precision definition.
  댓글 수: 4
Matt Fig
Matt Fig 2011년 4월 6일
Yes, if you know the limit, you can do
b(isnan(b)) = 2;
Stian Molvik
Stian Molvik 2011년 4월 6일
Ah. Ok. Hoped there would be an easier way, but still.
Thank you very much everyone for your help! :)

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

추가 답변 (3개)

Walter Roberson
Walter Roberson 2011년 4월 6일
In order to avoid this, you will need to use the symbolic toolbox.
MATLAB is giving the correct numeric answer according to IEEE 754 floating point definitions. MATLAB works with actual values computed on real machines, not with limits or ideal values. See for example this portion of the FAQ

Sean de Wolski
Sean de Wolski 2011년 4월 6일
0/0 is the definition of a nan
doc nan

Stian Molvik
Stian Molvik 2011년 4월 6일
Thanks for the reply Walter.
I haven't had too much experience with Matlab earlier. How would I go about using the symbolic toolbox?
  댓글 수: 1
Walter Roberson
Walter Roberson 2011년 4월 6일
Try this:
sym a
b = (1-a)*2/(1-a);
and see what b contains afterwards.

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by