今天在
Pycharm
編譯器中使用
round()
函數的時候編譯器提示了警告,後經修改去掉了警告,這裡做一下記錄。
代碼如下:
import numpy as np
x = np.array([0, 1])
y = np.sum(np.sin(x))
print(f"x四捨六入五留雙後的值為{round(y, 3)}")
編譯器提示資訊:
事實上,在有些情況下,編譯器會直接報錯,代碼如下:
import numpy as np
x = np.array([1])
y = x + 0.2732
print(f"x四舍五入後的值為{round(y, 3)}")
此時會提示:
numpy
的
ndarray
類型沒有
round()
函數。那麼為了避免和警告資訊的出現,我們可以使用一下兩種方式來解決這個問題。
方法一:使用類型強制轉換
import numpy as np
x = np.array([1])
y = x + 0.2732
print(f"x四捨六入五留雙後的值為{round(float(x), 3)}")
"""
result:
x四捨六入五留雙後的值為1.273
"""
方法二:使用
np.round()
函數
import numpy as np
x = np.array([1])
y = x + 0.2732
print(f"x四捨六入五留雙後的值為{np.round(y, 3)}")
"""
result:
x四捨六入五留雙後的值為[1.273]
"""