python - Round the number to its nearest base 10 number -




i want nearest base 10 number (ex. 10, 100, 1000) called new_n of input n. example, 99 gets 100 (not 10), 551 gets 1000 (not 100).

what try using np.log10 extract power of input number n , use power 10

import numpy np  n = 0.09 new_n = 10**(int(round(np.log10(n)))) print new_n  n = 35 new_n = 10**(int(round(np.log10(n)))) print new_n  n = 999 new_n = 10**(int(round(np.log10(n)))) print new_n  n = 4655 new_n = 10**(int(round(np.log10(n)))) print new_n  > 0.1 > 100 > 1000 > 10000 

the problem number such 35 np.log10(n) (which expect use power) 1.544068 , rounding 2. result 100instead of 10. or result of 4655 10000. how round number nearest base 10 number?

add check in linear space (with possible correction) after obtaining exponent:

n = np.array([0.09,35,549,551,999,4655]) e = np.log10(n).round() #array([-1.,  2.,  3.,  3.,  3.,  4.]) 

so, number closer "rounded" answer or previous degree of 10?

new_n = np.where(10**e - n <= n - 10**(e - 1), 10**e, 10**(e - 1)) #array([  1.00000000e-01,   1.00000000e+01,   1.00000000e+02, #         1.00000000e+03,   1.00000000e+03,   1.00000000e+03]) 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -