Python 中 Numpy 和 MpMath 之间的互操作性 [英] Interoperability between Numpy and MpMath in Python

查看:68
本文介绍了Python 中 Numpy 和 MpMath 之间的互操作性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 numpy 数组 A,其中 mpf 元素的十进制精度为 100.如果我决定将 A 的 numpy 点积与它本身一起使用,这个精度会被抛弃吗?

I have a numpy array A with mpf elements that have decimal precision 100. Is this precision cast away if I decide to take the numpy dot product of A with itself?

如果是这种情况,有什么方法可以将 numpy 数组转换为 mpmath 矩阵,这样我就可以保持精度吗?

If this is the case, is there any way to convert a numpy array to an mpmath matrix, so I can keep the precision?

推荐答案

Numpy 数组可以容纳对象,特别是 mpf 对象,它们的方法如 dot 可以使用这些对象的加法/乘法方法.示例:

Numpy arrays can hold objects, in particular mpf objects, and their methods such as dot can use the addition/multiplication methods of these objects. Example:

import mpmath
import numpy
mpmath.mp.dps = 25     # higher precision for demonstration
a = [mpmath.sin(mpmath.pi*n/3) for n in range(99)]
b = numpy.array(a)
b.dot(b)

输出 mpf('49.50000000000000000000000165')

为了比较,如果在转换为 numpy 时将数组元素强制转换为双精度浮点数会发生以下情况:

For comparison, this is what happens if the array elements are cast to double-precision floats when converting to numpy:

c = numpy.array(a, dtype=float)
c.dot(c)

输出 49.499999999999993.因此,在第一个版本中调用 dot 方法时,保留了 mpmath 提供的更高的精度.

outputs 49.499999999999993. So, the higher precision provided by mpmath is preserved when the dot method is invoked in the first version.

这篇关于Python 中 Numpy 和 MpMath 之间的互操作性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆