problem of Accuracy in vectors
3 次查看(过去 30 天)
显示 更早的评论
when i try to create a vector using (for example):
x=0:0.5000000001:3
x =
0 0.5000 1.0000 1.5000 2.0000 2.5000
>>
i get the resault above i wanted the vector to be until 3 but it's until 2.500000
to solve this problem i have not so ideal solution (i will explain why)
>> y=linspace(0,3,12)
y =
Columns 1 through 10
0 0.2727 0.5455 0.8182 1.0909 1.3636 1.6364 1.9091 2.1818 2.4545
Columns 11 through 12
2.7273 3.0000
>>
this function "linspace" is not linear function, the space between each and every array is different and you can see that by doint diff(y) and to see that the difference between the arrays is different
is there another solution for my problem (other function, other method....)? and why in the first method the vector is up to 2.5 and not 3?
0 个评论
回答(2 个)
Jan
2014-4-7
编辑:Jan
2014-4-7
Look at the documentation of the colon operator: 0:0.5000000001:3 creates:
[0, 0.5000000001, 1.0000000002, 1.5000000003, 2.0000000004, 2.5000000005]
The next element would be 3.0000000006, which is obviously greater than 3 and in consequence not included in the output.
There are very tiny difference between the elements of diff(y), because the numbers are represented with a limited precision only. You cannot store an arbitrary number of digits in a limited chunk of memory. See FAQ: Why is 0.3-0.2-0.1 not 0
0 个评论
José-Luis
2014-4-7
Please try:
0:2:3
You will see that it will not return 3. That is because the behavior of the colon operator is such that it will not include the upper limit if it is not equal to the lower limit plus a multiple of the interval, give or take numerical precision.
For instance:
0:0.50000000000000000000000000000001:3
would work as you expect.
As for linspace(), I am afraid I don't undertand what you mean. It IS linear. If you do
diff(linspace(0,3,12))
you will see that the values you get, while very similar, are not identical, and that is due to the numerical precision of double values. Please look at:
You should always be careful when comparing doubles.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!