How to mpf an array?

2019-01-23 06:57发布

问题:

I have:

import numpy as np
from mpmath import *

mpf(np.array(range(0,600)))

But it won't let me do it:

TypeError: cannot create mpf from array

So what should I be doing?

Essentially I'm going to have use this array and multiply element-wise with an incredibly large or incredible small number depending on circumstance (eg 1.35626567e1084 or 6.2345252e-2732) hence the need for mpf.

More specifically I'll be using the besseli and besselk function which create the incredible large and incredible small values.

How do I get an mpf array to hold these numbers?

回答1:

Multiplying an array by a mpf number just works:

import numpy as np
import mpmath as mp
small_number = mp.besseli(400, 2)  # This is an mpf number
# Note that creating a list using `range` and then converting it
# to an array is not very efficient. Do this instead:
A = np.arange(600)
result = small_number * A  # Array of dtype object, ie, it contains mpf numbeers

Multiplying element-wise two arrays containing mpf numbers also works:

result * result

So your real problem is how to evaluate an mpmath function in a numpy array. To do that, I'd use np.frompyfunc (some time ago this was the only option).

besseli_vec = np.frompyfunc(mp.besseli, 2, 1)
besseli_vec(0, A)


回答2:

Check out mpmath.arange:

import numpy as np
import mpmath as mp

np.array(mp.arange(600))