Problem with the ceil-operator
1 次查看(过去 30 天)
显示 更早的评论
Hello,
I have written the simple function, which determines the logarithm to base b of x.
function [y] = logBase(b,x)
y = log(x)/log(b);
end
Recently, I've observed a weird behaviour. If I determine ceil(y), I got wrong results for specific values.
For example: We know, that the logarithm of 125 to the base 5 is 3. When I let Matlab calculate it, it outputs 3.000. Now when I take the ceil-operator, I get 4 instead 3.
I think it has something to do with the form of the logBase-output. It outputs 3.0000 and ceil(3.000) outputs 4. But it should be 3.
Can someone help me with my problem? Thank You!
0 个评论
回答(2 个)
Stephen23
2017-11-17
编辑:Stephen23
2017-11-17
There is nothing wrong with ceil, and there is no "weird behavior".
You need to learn that computers do not have infinite precision, and that computing with floating-point numbers is not the same thing as performing mathematical symbolic operations.
Floating point numbers are how decimal values are stored in your computer: they do not have infinite precision, and they can only approximate many values. Even if it looks like the "actual" value is being shown to you this does not mean that the internal representation inside your computer is the same value.
Of course this means that every operation you perform on floating point values will accumulate these errors. It is up to you (and every other programmer) to design programs that take this "floating point error" into account.
Read all about it:
And if you want to see what the decimal equivalent of a floating point value is, then try this FEX submission:
As its author points out: "Don't confuse the exact conversion with significance!"
0 个评论
Matt J
2017-11-17
编辑:Matt J
2017-11-17
A solution is as follows,
function [y] = logBaseCeil(b,x)
%Lowest integer upper bound to log_b(x)
y=round(log(x)/log(b));
if x>b^y, y=y+1;end
end
When x and b are integers, the test x>b^y involves only integer arithmetic, and so is robust to the floating point issues mentioned by Stephen.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 NaNs 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!