【问题标题】:tuple to numpy, data accuracy元组到numpy,数据准确性
【发布时间】:2022-12-09 15:43:32
【问题描述】:

当我将元组转换为 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]

为什么?

【问题讨论】:

    标签: python numpy floating-accuracy


    【解决方案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')
    

    【讨论】:

    • @June-Solstice dtype 仅为float。请检查我的答案。
    【解决方案2】:

    这种看似差异应该只是数字的显示方式,而不是它们的表示/存储方式。

    您可以检查 dtype 以验证它仍然是 float64

    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]
    

    【讨论】:

      【解决方案3】:

      我想你只是看到了一个截断展示只是,但是内部值仍然保持原来的精度.这是我发现的:

      >> 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
      

      因此,没有理由更改任何设置 - 使用这些数组执行的数学运算仍将完全准确。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-25
        • 1970-01-01
        相关资源
        最近更新 更多