How would I manage to perform math.ceil
such that a number is assigned to the next highest power of 10?
# 0.04 -> 0.1 # 0.7 -> 1 # 1.1 -> 10 # 90 -> 100 # ...
My current solution is a dictionary that checks the range of the input number, but it's hardcoded and I would prefer a one-liner solution. Maybe I am missing a simple mathematical trick or a corresponding numpy function here?
Use the round() function to round a number to the nearest 10, e.g. result = round(num, -1) . When the round() function is called with a second argument of -1 , it rounds to the closest multiple of 10.
Python has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.
You can use math.ceil
with math.log10
to do this:
>>> 10 ** math.ceil(math.log10(0.04)) 0.1 >>> 10 ** math.ceil(math.log10(0.7)) 1 >>> 10 ** math.ceil(math.log10(1.1)) 10 >>> 10 ** math.ceil(math.log10(90)) 100
log10(n)
gives you the solution x
that satisfies 10 ** x == n
, so if you round up x
it gives you the exponent for the next highest power of 10.
Note that for a value n
where x
is already an integer, the "next highest power of 10" will be n
:
>>> 10 ** math.ceil(math.log10(0.1)) 0.1 >>> 10 ** math.ceil(math.log10(1)) 1 >>> 10 ** math.ceil(math.log10(10)) 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With