So, I've been doing a project lately and I come upon this interesting bug.
here's a variable W which uses the euler's formula i.e., cos(2*pi*1i/8) +
W = cos(2*pi/8) + sin(2*pi/8);
or even the exponent form
W = exp(2*pi*1i/8);
Now, if i use a power k = 2 on this variable, I get the result as intended
>> k = 2
k =
2
>> W^k
ans =
0.0000 + 1.0000i
Here's the one in a loop in the command window which is fine again
for k = 1:4
disp(W^(k-1));
end
1
0.7071 + 0.7071i
0.0000 + 1.0000i
-0.7071 + 0.7071i
but, when i put this in a loop inside my program this is the result
for k = 1:4
g(k) = W^(k-1);
disp("W^(k-1) " + W^(k-1));
end
W^(k-1) 1
W^(k-1) 0.70711+0.70711i
W^(k-1) 2.2204e-16+1i
W^(k-1) -0.70711+0.70711i
how did this bug occur such that it's working perfectly fine in commands but not in program ?

 採用された回答

Rik
Rik 2020 年 9 月 26 日

1 投票

This is not a bug. Look at the exponent: 2e-16 is very small. It is close enough to eps that you can assume that is just 0.
The reason in the way computers store values. Just like you can't store the result of 1/3, computers can't store every number. If you can only store 4 decimals 3*(1/3) will be 0.9999, not 1.

2 件のコメント

Aswin Prasanna Suriya Prakash
Aswin Prasanna Suriya Prakash 2020 年 9 月 26 日
I see.
But somehow I'm in the impression that this negligible number is completely ruining my final result. Is there any way to rectify this so the results of its iterations won't get affected also ?
Rik
Rik 2020 年 9 月 26 日
You probably don't have to do anything, but you could round to some maximum precision.

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

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

製品

リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by