具有mpz/mpfr值的numpy数组 [英] numpy array with mpz/mpfr values

查看:68
本文介绍了具有mpz/mpfr值的numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个具有mpz/mpfr值的numpy数组.因为我的代码:

I want to have a numpy array with mpz/mpfr values. Because my code:

import numpy as np
import gmpy2
A=np.ones((5,5));
print A/gmpy2.mpfr(1);

生成:

RuntimeWarning: invalid value encountered in divide
  print A/gmpy2.mpfr(1);
[[1.0 1.0 1.0 1.0 1.0]
 [1.0 1.0 1.0 1.0 1.0]
 [1.0 1.0 1.0 1.0 1.0]
 [1.0 1.0 1.0 1.0 1.0]
 [1.0 1.0 1.0 1.0 1.0]]

据我所知,不可能将gmpy mpfr转换为numpy float64.那么如何首先获得一个带有mpfr值的numpy数组?

Which as I can understand is the impossibility to convert gmpy mpfr to numpy float64. So how can I get a numpy array with mpfr values in the first place?

谢谢.

推荐答案

您将需要使用dtype=object创建数组,然后可以在数组中使用任何python类型.我没有安装gmpy2,但以下示例应显示其工作原理:

You will need to create your array with dtype=object, and then you can use any python type inside your array. I don't have gmpy2 installed, but the following example should show how it works:

In [3]: a = np.ones((5, 5), dtype=object)

In [5]: import fractions

In [6]: a *= fractions.Fraction(3, 4)

In [7]: a
Out[7]: 
array([[3/4, 3/4, 3/4, 3/4, 3/4],
       [3/4, 3/4, 3/4, 3/4, 3/4],
       [3/4, 3/4, 3/4, 3/4, 3/4],
       [3/4, 3/4, 3/4, 3/4, 3/4],
       [3/4, 3/4, 3/4, 3/4, 3/4]], dtype=object)

具有dtype=object的numpy数组可能会引起误导,因为默认对象的python运算符现在可以处理使使用标准dtypes进行运算的功能强大的numpy运算,这意味着速度会提高不再存在:

Having a numpy array of dtype=object can be a liitle misleading, because the powerful numpy machinery that makes operations with the standard dtypes super fast, is now taken care of by the default object's python operators, which means that the speed will not be there anymore:

In [12]: b = np.ones((5, 5)) * 0.75

In [13]: %timeit np.sum(a)
1000 loops, best of 3: 1.25 ms per loop

In [14]: %timeit np.sum(b)
10000 loops, best of 3: 23.9 us per loop

这篇关于具有mpz/mpfr值的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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