我通常使用
x = round(x, 3)
將數字四舍五入到 3 位數的精度。現在我有這個陣列:
[-1.10882605e-04 -2.01874994e-05 3.24209095e-05 -1.56917988e-05
-4.61406358e-05 1.99080610e-05 7.04079594e-05 2.64600122e-05
-3.53022316e-05 1.50542793e-05]
使用相同的代碼只會將所有內容都壓縮為 0。不過我想要的是一個函式,它可以為我提供最重要的 3 位四舍五入數字,就像它通常適用于大于 1 的數字一樣。像這樣:
special_round(0.00034567, 3)
=
0.000346
知道如何做到這一點嗎?謝謝!
uj5u.com熱心網友回復:
這是一個計算數量級并進行元素明智舍入的解決方案。
請注意,這僅適用于值 < 1 和 > -1,我猜這是關于您的示例資料的有效假設。
import numpy as np
a = np.array([-1.10882605e-04, -2.01874994e-05, 3.24209095e-05, -1.56917988e-05,
-4.61406358e-05, 1.99080610e-05, 7.04079594e-05 , 2.64600122e-05,
-3.53022316e-05 , 1.50542793e-05])
def special_round(vec):
exponents = np.floor(np.log10(np.abs(vec))).astype(int)
return np.stack([np.round(v, decimals=-e 3) for v, e in zip(vec, exponents)])
b = special_round(a)
>>> array([-1.109e-04, -2.019e-05, 3.242e-05, -1.569e-05, -4.614e-05,
1.991e-05, 7.041e-05, 2.646e-05, -3.530e-05, 1.505e-05])
uj5u.com熱心網友回復:
問題是,您提供的數字開始變得如此之小,以至于您正在接近浮點精度的極限,因此似乎無緣無故地出現了一些工件。
def special_round(number, precision):
negative = number < 0
number = abs(number)
i = 0
while number <= 1 or number >= 10:
if number <= 1:
i = 1
number *= 10
else:
i = -1
number /= 10
rounded = round(number, precision)
if negative:
rounded = -rounded
return rounded * (10 ** -i)
輸出:
[-0.0001109, -2.019e-05, 3.2420000000000005e-05, -1.569e-05, -4.614e-05, 1.9910000000000004e-05, 7.041000000000001e-05, 2.646e-05, -3.5300000000000004e-05, 1.505e-05]
uj5u.com熱心網友回復:
您可以通過使用math包創建特定函式來實作:
from math import log10 , floor
import numpy as np
def round_it(x, sig):
return round(x, sig-int(floor(log10(abs(x))))-1)
a = np.array([-1.10882605e-04, -2.01874994e-05, 3.24209095e-05, -1.56917988e-05,
-4.61406358e-05, 1.99080610e-05, 7.04079594e-05, 2.64600122e-05,
-3.53022316e-05, 1.50542793e-05])
round_it_np = np.vectorize(round_it) # vectorize the function to apply on numpy array
round_it_np(a, 3) # 3 is rounding with 3 significant digits
這將導致
array([-1.11e-04, -2.02e-05, 3.24e-05, -1.57e-05, -4.61e-05, 1.99e-05,
7.04e-05, 2.65e-05, -3.53e-05, 1.51e-05])
uj5u.com熱心網友回復:
這是一個解決方案:
from math import log10, ceil
def special_round(x, n) :
lx = log10(abs(x))
if lx >= 0 : return round(x, n)
return round(x, n-ceil(lx))
for x in [10.23456, 1.23456, 0.23456, 0.023456, 0.0023456] :
print (x, special_round(x, 3))
print (-x, special_round(-x, 3))
輸出:
10.23456 10.235
-10.23456 -10.235
1.23456 1.235
-1.23456 -1.235
0.23456 0.235
-0.23456 -0.235
0.023456 0.0235
-0.023456 -0.0235
0.0023456 0.00235
-0.0023456 -0.00235
uj5u.com熱心網友回復:
您可以使用常用對數(由內置數學模塊提供)來計算數字中第一個有效數字的位置(2 代表百位,1 代表十位,0 代表個位,-1 代表 0 .x, -2 代表 0.0x 等等...)。知道第一個有效數字的位置,您可以使用它來正確舍入數字。
import math
def special_round(n, significant_digits=0):
first_significant_digit = math.ceil((math.log10(abs(n))))
round_digits = significant_digits - first_significant_digit
return round(n, round_digits)
>>> special_round(0.00034567, 3)
>>> 0.000346
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/384724.html
