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!