Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python round to next highest power of 10

Tags:

python

ceil

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?

like image 210
offeltoffel Avatar asked Apr 03 '20 09:04

offeltoffel


People also ask

How do you round a number to the next 10 in Python?

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.

How do you round to next value in Python?

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.


1 Answers

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 
like image 185
jonrsharpe Avatar answered Sep 17 '22 14:09

jonrsharpe