An integer in scientific notation is not read as an integer?

5 ビュー (過去 30 日間)
Albert Lin
Albert Lin 2018 年 4 月 16 日
コメント済み: Jan 2018 年 4 月 16 日
Hello, I am trying to create a zero array of one million and one entries. Here's what I have:
nt = 10/(1E-5)+1;
theta = zeros(1,nt);
However, there was an error message saying "Error using zeros: size inputs must be integers." I tried inputting "zeros(1,1000001);" and the code miraculously worked. How is this possible? Is there a way to create an array in terms of my variable "nt"? Thanks!
  1 件のコメント
Jan
Jan 2018 年 4 月 16 日
Welcome to the world of numeric with floating point numbers stored with limited precision.
a = 10/(1E-5)+1
b = 1000001
a - b
This is not zero, but -1.164e-10.

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

回答 (1 件)

Stephen23
Stephen23 2018 年 4 月 16 日
編集済み: Stephen23 2018 年 4 月 16 日
theta = zeros(1,round(nt));

The problem with your code is that you did not take into account the floating point error in the calculation. Floating-point numbers have been explained many times on this forum:

https://www.mathworks.com/matlabcentral/answers/57444-faq-why-is-0-3-0-2-0-1-not-equal-to-zero

https://www.mathworks.com/matlabcentral/answers/69-why-does-1-2-3-1-3-not-equal-zero#answer_271

https://www.mathworks.com/matlabcentral/answers/316889-why-two-equal-numbers-are-not-equal

https://www.mathworks.com/matlabcentral/answers/41536-why-is-2-24-10-22-4-not-equal-to-0

https://www.mathworks.com/matlabcentral/answers/20830-1-0010-does-not-equal-1-0010

etc, etc, etc

If you look at the exact values of 1E-5 you will find that it is not an exact power of ten, so from that point on the floating point error propagates through your calculation and thus the entire calculation will not give an integer output. Try this for an approximation:

sprintf('%.40f',1e-5)

Or download this to see the exact value:

https://www.mathworks.com/matlabcentral/fileexchange/22239-num2strexact--exact-version-of-num2str-

カテゴリ

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