12

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?

Doubt
  • 1,163
  • 2
  • 15
  • 26
Rapid
  • 1,442
  • 1
  • 13
  • 25

2 Answers2

16

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)
jorgeca
  • 5,482
  • 3
  • 24
  • 36
  • Thank you so much. I was just about to give up and use sluggish for loops! You mention this was the only option some time ago, what are the other options nowadays? – Rapid Dec 07 '12 at 09:16
  • 4
    @Rapid A quick google search seems to imply that it's still the only way. That's understandable since this option is so simple. – jorgeca Dec 07 '12 at 11:33
  • I am having same issue in a different setting and I just linked my post to this page. Would appreciate any help, – Rebel Nov 21 '17 at 07:01
  • So when I have to multiply a np.array I happen to have by some mpf number there is no point in first converting the np.array to mpf and then multiplying it with the mpf number? The result will be the same (same accuracy) as directly performing the multiplication? – Kvothe Apr 22 '21 at 16:14
3

Check out mpmath.arange:

import numpy as np
import mpmath as mp

np.array(mp.arange(600))
endolith
  • 25,479
  • 34
  • 128
  • 192
Arsh Singh
  • 2,038
  • 15
  • 16
  • I still can't do this `A=np.array(arange(600))` followed by `besseli(0,A)` without it throwing errors at me? – Rapid Dec 06 '12 at 14:21