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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by