开发者

Rounding to a power of 10

I have a variable, tauMax, that I want to round up to the nearest power of ten(1, 10, 100, 1000...). I am using the below expression to find the closest integer to the max value in the tau array. I am finding the max value because I am trying to calculate the power of ten that should be the x axis cutoff. In this cause, tauMax is equal to 756, so I want to have an expression that outputs either 1000, or 3(for 10^3).

tauMax = round(max(tau));

I'd real开发者_Python百科ly appreciate any help!


Since you're talking base 10, you could just use log10 to get the number of digits.

How about:

>> ceil(log10(756))

ans =

     3


I don't really do Matlab, but the usual way to do this in any language I do know is: take the logarithm base 10, then round up that number to the nearest integer, then compute 10 to the power of that number. In Python:

from math import ceil, log

def ceil_power_of_10(n):
    exp = log(n, 10)
    exp = ceil(exp)
    return 10**exp

>>> print(ceil_power_of_10(1024))  # prints 10000


You could also look at the source of the built-in Matlab function nextpow2(N) (simply open nextpow2.m) to see how Mathworks engineers implemented this for a power of 2 and create a new function adapting this source to a power of 10.

http://www.mathworks.it/it/help/matlab/ref/nextpow2.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜