代码之家  ›  专栏  ›  技术社区  ›  June-Solstice

元组到numpy,数据准确性

  •  0
  • June-Solstice  · 技术社区  · 2 年前

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

    请帮忙。

    3 回复  |  直到 2 年前
        1
  •  0
  •   Mayank Porwal    2 年前

    一种方法是设置:

    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')
    
        2
  •  0
  •   Demis    2 年前

    我想你只看到了 陈列 仅,但内部值仍保持更高的准确性。以下是我的发现:

    >> a
    (0.547693688614422, -0.7854270889025808, 0.6267478456110592)
    
    >> b=np.array(a)
    
    >> b
    array([ 0.54769369, -0.78542709,  0.62674785])
    
    >> b[0]
    0.547693688614422
    
        3
  •  0
  •   Capybara    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]