6

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

更准确地说,我需要在 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 循环)

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

4

1 回答 1

4

Your second method is to be preferred, but using np.float32 means casting numbers to single precision. For your matrix, this precision is too low: 115.80200375 becomes 115.80200195 due to truncation. You can set double precition explicitly with numpy.float64, or just pass Python's float type as an argument, which means the same.

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

or, to keep the matrix structure,

Z = numpy.matrix(matr.tolist(), dtype=float)
于 2016-04-24T19:55:51.320 回答