简体   繁体   English

将数字四舍五入至最接近的基数10

[英]Round the number to its nearest base 10 number

I want to get the nearest base 10 number (ex. 10, 100, 1000) called new_n of the input n . 我想获得输入n的最接近的以10为底的数字(例如new_n ),称为new_n For example, 99 gets 100 (not 10 ), 551 gets 1000 (not 100 ). 例如, 99得到100 (不是10 ), 551得到1000 (不是100 )。

What I try is using np.log10 to extract the power of the input number n and use it to power 10 我尝试使用np.log10提取输入数字n的幂并使用它来幂10

import numpy as 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 is the number such as 35 its np.log10(n) (which I expect to use as power) is 1.544068 and its rounding is 2 . 问题是数字如35np.log10(n) (我希望用作电源)为1.544068 ,其舍入为2 So the result is 100 instead of 10 . 因此,结果是100而不是10 Or the result of 4655 is 10000 . 4655的结果是10000 How to round the number to the nearest base 10 number? 如何将数字四舍五入到最接近的基数10?

Add a check back in the linear space (with a possible correction) after obtaining the exponent: 获得指数后,在线性空间中添加一个检查(可能会进行校正):

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

So, is the number closer to the "rounded" answer or to the previous degree of 10? 那么,这个数字是更接近“四舍五入”的答案还是接近先前的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])

You can achieve what you want by scaling your numbers before taking the logs. 您可以通过在记录日志前缩放数字来实现所需的功能。 Multiply each value by sqrt(10) / 5.5 and you should get the results you want: 将每个值乘以sqrt(10) / 5.5 ,您应该得到想要的结果:

n = np.array([0.09,35,549,551,999,4655]) # borrowed test values from @DYZ
multiplier = np.sqrt(10) / 5.5
results = 10**np.log10(multiplier * n).round()
# array([  1.00000000e-01,   1.00000000e+01,   1.00000000e+02,
#          1.00000000e+03,   1.00000000e+03,   1.00000000e+03])

You can try this one: 您可以尝试以下一种方法:

import np
new_n = 10**(np.floor(np.log10(n)-np.log10(0.5)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM