how to save variables not in scientific notation

14 ビュー (過去 30 日間)
Nick Thomas
Nick Thomas 2018 年 4 月 22 日
コメント済み: Walter Roberson 2018 年 4 月 22 日
I have certain variables saving in scientific notation. I am trying to use them in creating a matrix, for example:
nc = 19840; %saves the variable as 1.9840e+04
A = ones(nc,nc)
When I try to do this, I get the following error:
Error using ones
Size inputs must be integers.
I guess Matlab isn't reading it as an integer? Is there a way to make it save the variable not in scientific notation? (I don't have the problem with anything not saved in sci notation) I've tried things like sprintf and num2str without luck.
  4 件のコメント
Stephen23
Stephen23 2018 年 4 月 22 日
編集済み: Stephen23 2018 年 4 月 22 日

@Nick Thomas: please show the output of these operations:

>> nc - 19840
>> whos nc
Nick Thomas
Nick Thomas 2018 年 4 月 22 日
編集済み: Walter Roberson 2018 年 4 月 22 日
>> nc-19840
ans =
     3.6380e-12
>> whos nc
    Name      Size            Bytes  Class     Attributes
    nc        1x1                 8  double              

This is interesting, now I see that it's somehow storing a small decimal amount with the value. It doesn't make sense to me why though, here is my code for calculating nc along with the variables used.

nb = 128;
h = 0.2;
t_s = 0.004;
t_i = 0.05;
s = 500;
nc = nb+(nb*((h+2*t_s+2*t_i)*s));

So there is no reason I should be having a weird decimal at the end.

Knowing this I fixed the problem using the round(x,0) command. However, I'm still curious as to why this happened?

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

採用された回答

the cyclist
the cyclist 2018 年 4 月 22 日

The reason is that the intermediate values in your calculation cannot be stored exactly. Here is one starting point for understanding why that is.

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2018 年 4 月 22 日
  1 件のコメント
Walter Roberson
Walter Roberson 2018 年 4 月 22 日
syms deltah
nb = sym(128, 'r');
h = sym(0.2, 'r') + deltah;
t_s = sym(0.004, 'r');
t_i = sym(0.05, 'r');
s = sym(500, 'r');
nc = nb+(nb*((h+2*t_s+2*t_i)*s));
nc
subs(nc, deltah, eps(0.2))
vpa(ans)
nc =
64000*deltah + 19840
ans =
1396115884484853885/70368744177664
ans =
19840.00000000000177635683940025

You can see from this that a difference of 1 bit in the representation of 0.2 makes a difference of

>> vpa(subs(nc,deltah,eps(0.2)) - 19840)
ans =
0.0000000000017763568394002504646778106689453

0.2 is not exactly representable in binary floating point: it is an infinite repeating decimal, just like 1/7 is not exactly representable in finite decimal.

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

カテゴリ

Help Center および File ExchangeConversion Between Symbolic and Numeric についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by