python - 如何正确地将 mpmath 矩阵转换为 numpy ndarray(并将 mpmath.mpf 转换为 float )

标签 python numpy matrix type-conversion mpmath

我正在使用 mpmath python 库在某些计算期间获得精度,但我需要将结果转换为 numpy native 类型。

更准确地说,我需要在 numpy.ndarray(包含浮点类型)中转换一个 mpmath 矩阵(包含 mpf 对象类型)。

我已经用原始方法解决了这个问题:

# My input Matrix:

matr = mp.matrix(
[[ '115.80200375',  '22.80402473',   '13.69453064',   '54.28049263'],
[  '22.80402473',   '86.14887381',   '53.79999432',   '42.78548627'],
[  '13.69453064',   '53.79999432',  '110.9695448' ,   '37.24270321'],
[  '54.28049263',   '42.78548627',   '37.24270321',   '95.79388469']])

# multiple precision computation
D = MPDBiteration(matr)

# Create a new ndarray  
Z = numpy.ndarray((matr.cols,matr.rows),dtype=numpy.float)

# I fill it pretty "manually"
for i in range(0,matr.rows):
    for j in range(0,matr.cols):
        Z[i,j] = D[i,j] # or float(D[i,j]) seems to work the same

我的问题是:

是否有更好/更优雅/更简单/更聪明的方法来做到这一点?

更新:

反复阅读 mpmath 文档,我发现这个非常有用的方法:tolist() ,它可以按如下方式使用:

 Z = np.array(matr.tolist(),dtype=np.float32)

看起来稍微好一点和优雅(不需要 for 循环)

有更好的方法吗?我的第二个解决方案是四舍五入还是砍掉多余的数字?

最佳答案

您的第二种方法是首选,但使用 np.float32 意味着将数字转换为单精度。对于您的矩阵,此精度太低:115.80200375 由于截断而变为 115.80200195。您可以使用 numpy.float64 显式设置 double ,或者只将 Python 的 float 类型作为参数传递,这意味着相同。

Z = numpy.array(matr.tolist(), dtype=float)

或者,为了保持矩阵结构,

Z = numpy.matrix(matr.tolist(), dtype=float)

关于python - 如何正确地将 mpmath 矩阵转换为 numpy ndarray(并将 mpmath.mpf 转换为 float ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28446555/

相关文章:

python - 是否可以在 django 中创建表单,让您直接在数据库中更改或添加?

python - numpy:int 是一个 basestring?

python - 这种一次性矢量转换是如何工作的?

python - numpy 中的特定张量积

python - 在 Python 中从 FFT 或 RFFT 查找 FFT 系数

python - 无法在 Django 中运行 Scrapy 项目

matlab - 在 MATLAB 中向量化矩阵的加权和

Perl 通过动态规划在序列对齐中爆炸

python - 在Python中执行一个文件(安装程序)并立即退出

python - ValueError : The truth value of array with more than one element is ambiguous. 使用 a.any() 或 a.all()