MATLAB Answers

Problem with the ceil-operator

9 views (last 30 days)
Nik joung
Nik joung on 17 Nov 2017
Edited: Stephen Cobeldick on 17 Nov 2017
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 Comments

Sign in to comment.

Answers (2)

Stephen Cobeldick
Stephen Cobeldick on 17 Nov 2017
Edited: Stephen Cobeldick on 17 Nov 2017
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 Comments

Sign in to comment.


Matt J
Matt J on 17 Nov 2017
Edited: Matt J on 17 Nov 2017
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 Comments

Sign in to comment.


Translated by