File Exchange

## Order of magnitude of number

version 1.1.0.0 (1.24 KB) by
Returns the order of magnitude of one or more numbers.

Updated 18 Jun 2012

Returns the order of magnitude of one or more numbers. Works on arrays. You can also specify the number base.

%Ex:
order( 1.2e-5 ) %returns -5
order(1) = 0
order( 1.12344e8 ) %returns 8
%Specify base 2:
order(1.2*2^5,2) %returns 5

### Cite As

Ivar Eskerud Smith (2021). Order of magnitude of number (https://www.mathworks.com/matlabcentral/fileexchange/28559-order-of-magnitude-of-number), MATLAB Central File Exchange. Retrieved .

John McDowell

Arislan Makhmudov

Alexandre Piccini

It seems the val = 1000 problem is taking place due to the intrinsic numerical imprecision of double vars really. Trying to account for numerical imprecision one can round the ratio of the logs within "floor" to the 15th decimal digit, as rounding to the 16th or lower still produces the same error. Therefore, line 8 will be this instead:

n = floor(round((log(abs(val))./log(base)),15));

Therefore, if you do
val = 1000;

log(abs(val))./log(base) - 3 ;
returns = -4.440892098500626e-16

round((log(abs(val))./log(base)),15) - 3
returns = 0.

Robert

If you input at the command line:

log(1000)./log(10) - 3

you will see why the original fails at this value. It also fails and a number of other (positive) powers of 10 as shown by the following:

b = -100:100
for q = 1:length(b)
a(q) = order(10^b(q));
end
figure(1)
plot(b, a, 'kx', b, b, 'ro')
grid on

If the black 'x' is not inside a red 'o' then it's a failure.
No failures of negative powers in this range.

Ben

Now tested with vector:

>> floor(single(log([1000 100 1000 10000 100])./log(10)))

ans =

3 2 3 4 2

Ivar Eskerud Smith

Joel, I seem to experience the same problem when the input is an exact integer value. I think this will be a problem when the input is a whole power of the base. I am not sure yet how this shuold be solved, one would have to do a test on the input to detect if it is a whole power of the base within numerical precision

Joel

I seem to experience a severe precision error using this function. I get order(1000) = 2. order(1000.000000000001) gives me the correct value of 3.

Irem Altan

Carlos

Thanks!

Ndilokelwa Luis

Efficient.

John

I see what you're doing and it makes sense, thanks for the reply!

Ivar Eskerud Smith

Thanks John. But I think one should leave the order of magnitude of 0 to be minus infinity, that`s just what it is. If you set it to zero, consider this:
x=0;
o = order(x);
x2=10^o;
x2 and x should then be the same, but they won`t be if you set the order to 0. x2 would then be 1.

John

added the following to the bottom:

% If the value is zero then the order is set to zero
n(isinf(n)) = 0;

John

works great!

##### MATLAB Release Compatibility
Created with R2012a
Compatible with any release
##### Platform Compatibility
Windows macOS Linux