Create mpf from array

橙三吉。 提交于 2019-12-02 09:32:51

The trick is to apply np.frompyfunc to a function instead of a value. I think the following modification would make your function work:

def cosFunc(p):
  vn = p
  np_sin = np.frompyfunc(mp.sin, 1, 1)
  output = np_sin(vn)
  return float(output)

value = fsolve(cosFunc, 1)
print value

The specific cause of the error you is this:

(Pdb) x0
array([mpf('1.0')], dtype=object)
(Pdb) mp.sin(x0)
*** TypeError: cannot create mpf from array([mpf('1.0')], dtype=object)

What happens is that fsolve tries to convert your estimate to array and numpy does not know how to handle mpmath objects.

>>> np.asarray(mp.mpf(1))
>>> array(mpf('1.0'), dtype=object)

Changing how fsolve works is not very productive, so your best bet seems to be to teach your function to handle arrays of mpmath objects

def cos_func(p):
   vn = p
   if isinstance(p, np.ndarray):
         if p.size == 0: 
             vn = p[0]
         else:
             raise ValueError  # or whatever you want to do here"
   return mp.sin(vn)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!