Doesnt overwrite Variable inside of Loop

2 ビュー (過去 30 日間)
Raz134
Raz134 2021 年 1 月 21 日
編集済み: Stephen23 2021 年 1 月 22 日
I am trying to overwrite the variable "anzahl_gamma" when gamma on the position t is equal to "g_s", g_s is 0.05
so "anzahl_gamma" should be 4 after my loop but it doesnt overwrite.
gamma = [0.005,0.01,0.025,0.0500,0.1,0.9,0.95,0.975,0.99,0.995];
signifikanzniveau = 0.95;
g_s = 1 - signifikanzniveau; % 0.05
anzahl_gamma=0;
for t = 1:10
if gamma(t)== g_s
anzahl_gamma = t;
end
end
Why does this give me anzahl_gamma=0;
and when i change g_s to 0.05 directly it works:
for t=1:10
if gamma(t)==0.05
anzahl_gamma=t;
end
end
with 0.05 directly i get anzahl_gamma=4;
What am i missing here? why is the first one (gamma(t)==g_s) not working?

採用された回答

Matt Gaidica
Matt Gaidica 2021 年 1 月 22 日
編集済み: Matt Gaidica 2021 年 1 月 22 日
gamma = int32([0.005,0.01,0.025,0.0500,0.1,0.9,0.95,0.975,0.99,0.995] * 1000);
signifikanzniveau = 0.95;
g_s = int32((1 - signifikanzniveau) * 1000); % 0.05
anzahl_gamma = 0;
for t = 1:10
if gamma(t) == g_s
anzahl_gamma = t;
end
end
There are a few ways to solve this. See here about floating point numbers. Also, beware gamma is a reserved function, I try to stay away from using those as variable names.
  2 件のコメント
Raz134
Raz134 2021 年 1 月 22 日
Thank you this worked. I didnt know that matlab cannot compare vectors if they do not consist of integer numbers. I think thats whats happening here?
But thank you very much!
Stephen23
Stephen23 2021 年 1 月 22 日
編集済み: Stephen23 2021 年 1 月 22 日
"I didnt know that matlab cannot compare vectors if they do not consist of integer numbers"
It can. But operations on the binary floating point numbers that your computer hardware supports (and that enable MATLAB to perform very fast and efficient HW operations for many numeric computations) by their very nature accumulate floating point error. This is simply a feature of binary floating point numbers.
It is up to the programmer to understand the behaviors of binary floating point numbers. For example, Iinstead of testing for exact equality, the recommended approach is to compare the absolute difference against a tolerance:
abs(A-B)<tol
Read more about binary floating point numbers:
This is worth reading as well:

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by