How to avoid NaN while evaluating a function

9 ビュー (過去 30 日間)
Ruye Wang
Ruye Wang 2013 年 5 月 16 日
The function below is always finite and reaches maximum y=1/4 when x=0. However, when x<0 and abs(x) is large, the numerator exp(-x) may return a NaN, causing the returned value of the function to be NaN as well, although the function should return a very small number (almost zero). What should I do to get the desired answer zero instead of an NaN?
function y=dg(x) y=exp(-x)./(1+exp(-x)).^2 end
Thanks!

回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 5 月 16 日
編集済み: Azzi Abdelmalek 2013 年 5 月 16 日
function y=dg(x)
y=exp(-x)./(1+exp(-x)).^2
y(isnan(y))=0

José-Luis
José-Luis 2013 年 5 月 16 日
If you have the symbolic math tool then you could use variable precision arithmetic. For instance, please try the following snippet:
myFun = @(x) vpa(exp(-x)./(1+exp(-x)).^2,1000);
test = myFun(500)
Which should return a value different from zero. The problem you are encountering is due to the finite numerical precision of doubles. If you don't have the toolbox you could look in the file exchange for alternatives that perform the same tasks, for example:

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by