Doesn't show the result as an integer even though the result of the operation is an integer

1 回表示 (過去 30 日間)
Yasin Sefa
Yasin Sefa 2023 年 12 月 27 日
コメント済み: Yasin Sefa 2023 年 12 月 28 日
clear all; clc; %close all;
global ii
dt=0.0001; %time step
t_final=2.27; % final time
Nt=t_final/dt; % last time
In the code above when t_final value is 2.25 or 2.27, Nt is an integer. As a matter of fact, the result is an integer. but why the result is not an integer when t_final value is 2.26.
t_final=2.26;
t_final=2.27;
  2 件のコメント
Stephen23
Stephen23 2023 年 12 月 28 日
編集済み: Stephen23 2023 年 12 月 28 日
"As a matter of fact, the result is an integer."
As a matter of fact, the result may or may not be an integer... but in either case are equally valid given the accuracy of binary floating point numbers and the accumulated floating point error of the given calculation.
"but why the result is not an integer when t_final value is 2.26"
That answer has been discussed many many many times:
These are worth reading as well:

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

回答 (3 件)

the cyclist
the cyclist 2023 年 12 月 27 日
編集済み: the cyclist 2023 年 12 月 27 日
See, for example, this question and answer.

Walter Roberson
Walter Roberson 2023 年 12 月 27 日
dt=0.0001;
fprintf('%.99g\n', dt)
0.000100000000000000004792173602385929598312941379845142364501953125
t_final=2.26;
fprintf('%.99g\n', t_final)
2.2599999999999997868371792719699442386627197265625
Nt = t_final ./ dt;
fprintf('%.99g\n', Nt)
22599.99999999999636202119290828704833984375
So you divide something that is not quite 226/100 by something that is not exactly 1/10000 and you get a result that is not quite 22560 .
You have made the mistake of thinking that MATLAB stores numbers in base 10. MATLAB uses the IEEE 754 Double Precision standard to store numbers.
  2 件のコメント
David Goodmanson
David Goodmanson 2023 年 12 月 28 日
編集済み: David Goodmanson 2023 年 12 月 28 日
Hi Yasin,
To supplement what Walter is saying, it's interesting to go to formax hex, which shows what is actually stored in memory. In IEEE 754 double precision a real number consists of 8 bytes = 64 binary digits. (Not all of the digits contribute to digits of the actual number since you need some to represent a floating point exponent, the algebraic sign, NaN ,inf etc). There are 2^64 possible values, which is 16 hexidecimal digits since 2^64 = 16^16. So
format hex
.0001
ans = 3f1a36e2eb1c432d
as opposed to a power of 2 of around the same size
2^(-13) % 1/8192
ans = 3f20000000000000
Clearly the representation of .0001 is truncated and approximate, whereas the representation of 2^-13 is exact.

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


Image Analyst
Image Analyst 2023 年 12 月 28 日

カテゴリ

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