提问人:June-Solstice 提问时间:6/2/2022 最后编辑:CapybaraJune-Solstice 更新时间:12/9/2022 访问量:99
元组到 numpy,数据准确性
tuple to numpy, data accuracy
问:
当我将元组转换为numpy时,数据准确性存在问题。我的代码是这样的:
import numpy as np
a=(0.547693688614422, -0.7854270889025808, 0.6267478456110592)
print(a)
print(type(a))
tmp=np.array(a)
print(tmp)
结果如下:
(0.547693688614422, -0.7854270889025808, 0.6267478456110592)
<class 'tuple'>
[ 0.54769369 -0.78542709 0.62674785]
为什么?
答:
0赞
Mayank Porwal
6/2/2022
#1
一种方法是设置以下内容:
In [1039]: np.set_printoptions(precision=20)
In [1041]: tmp=np.array(a)
In [1042]: tmp
Out[1042]: array([ 0.547693688614422 , -0.7854270889025808, 0.6267478456110592])
In [1043]: tmp.dtype
Out[1043]: dtype('float64')
评论
0赞
Mayank Porwal
6/2/2022
@June-Solstice dtype 只是。请查看我的答案。float
0赞
Demis
6/2/2022
#2
我认为您只在显示中看到截断,但内部值仍保持原始精度。这是我发现的:
>> a
(0.547693688614422, -0.7854270889025808, 0.6267478456110592)
>> b=np.array(a)
>> b
array([ 0.54769369, -0.78542709, 0.62674785]) #<-- printed display shows lower accuracy
>> b[0]
0.547693688614422 #<-- print of a single value shows same accuracy as original
因此,没有理由更改任何设置 - 使用这些数组执行的数学运算仍将是完全准确的。
0赞
Capybara
6/2/2022
#3
这种看似的差异应该只是数字的显示方式,而不是它们的表示/存储方式。
您可以检查以验证它仍然是 float64dtype
tmp.dtype # dtype('float64')
您可以调整以查看它们以不同的方式显示值np.set_printoptions
print(tmp) # [ 0.54769369 -0.78542709 0.62674785]
np.set_printoptions(precision=18) # default precision is 8
print(tmp) # [ 0.547693688614422 -0.7854270889025808 0.6267478456110592]
评论