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

4 Ansichten (letzte 30 Tage)
Albert Lin
Albert Lin am 16 Apr. 2018
Kommentiert: Jan am 16 Apr. 2018
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 Kommentar
Jan
Jan am 16 Apr. 2018
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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Stephen23
Stephen23 am 16 Apr. 2018
Bearbeitet: Stephen23 am 16 Apr. 2018
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-

Community Treasure Hunt

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

Start Hunting!

Translated by