Problems when creating matrix
3 次查看(过去 30 天)
显示 更早的评论
Hello,
I am trying to create a matrix by several means, using linespace, using matrix notation and stating every element. For some reason the results obtained are not equal for some of the values in the matrix:
categ1=linspace(0.85,1.35, 51)
categ2=[0.85:0.01:1.35]
categ3=[0.85 0.86 0.87 0.88 0.89 0.9 0.91 0.92 0.93 0.94 0.95 0.96 0.97 0.98 0.99 1 1.01 1.02 1.03 1.04 1.05 1.06 1.07 1.08 1.09 1.1 1.11 1.12 1.13 1.14 1.15 1.16 1.17 1.18 1.19 1.2 1.21 1.22 1.23 1.24 1.25 1.26 1.27 1.28 1.29 1.3 1.31 1.32 1.33 1.34 1.35]
categ1==categ2
categ2==categ3
0 个评论
回答(1 个)
Daniel M
2019-10-21
The results are equal up to double precision. Look at this:
max(abs(categ1-categ2))
% ans =
% 2.22044604925031e-16
eps
% ans =
% 2.22044604925031e-16
So the values are equal up to the limit that the computer can differentiate between them.
It seems that linspace and colon have slightly different implementations. If you need something with higher precision, then look into John D'Errico's VPI toolbox.
2 个评论
Stephen23
2019-10-22
编辑:Stephen23
2019-10-22
"Any idea of how can I solve that issue?"
Don't check for exact equality of floating point values.
Always check the absolute difference against a tolerance:
abs(A-B)<tol
The behaviors of floating point numbers are quite well documented, you need to learn how to write your code taking them into account. Start by reading these:
etc.etc.
This is worth reading as well:
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!