【问题标题】:printoptions formatter not working for a single element of an array of complex numbersprintoptions 格式化程序不适用于复数数组的单个元素
【发布时间】:2020-11-27 11:48:09
【问题描述】:

我不明白为什么这个格式化程序不能格式化complex128

import numpy as np
import scipy.sparse as sp

A = sp.diags([1, -2, 1], [1, 0, -1], shape=[3, 3], format='csc')
evals, evecs = sp.linalg.eigs(A, k=1, which='LM')

with np.printoptions(formatter={'complex_kind': '{:.2f}'.format}):
    print (evals, evals[0])

此代码显示一个单元素 numpy.ndarray,然后是元素。格式化程序用于数组,而不是单独用于元素:

[-3.41+0.00j] (-3.4142135623730954+0j)

涉及的类型:

type(evals): numpy.ndarray
evals.dtype: dtype('complex128')
type(evals[0]): numpy.complex128

任何线索表示赞赏。

【问题讨论】:

标签: python scipy format numpy-ndarray


【解决方案1】:

numpy.printoptionsnumpy.set_printoptions 的设置控制 NumPy 如何打印数组。它们不会影响 NumPy 标量(例如 numpy.complex128numpy.float32 等)的打印方式。

例如,

In [14]: np.set_printoptions(precision=3)                                       

In [15]: np.array([np.pi])  # A 1-d array.                                                                                          
Out[15]: array([3.142])

In [16]: np.array(np.pi)    # A 0-d array (aka a scalar array)                                                                        
Out[16]: array(3.142)

In [17]: np.float64(np.pi)  # A scalar float64. Output is not controlled by the print options                                       
Out[17]: 3.141592653589793

请参阅 NumPy github 站点上的 github issue 11048(以及那里提供的链接)以了解有关此主题的讨论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-13
    • 2012-01-24
    • 2015-01-28
    • 2016-12-28
    • 2019-04-26
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多