python-3.xmpmath

How to get values given by `mpmath`?


I have no experience in using mpmath package. I just recently used it for some small tests and had the following returns:

from mpmath import *
loggamma(3+2j)
mpc(real='-0.031639059373961193', imag='2.022193197501327')
atan2(2,3)
mpf('0.5880026035475675')

I would just like to know how to retrieve the real values indicated by mpmath (-0.031..., 2.022..., 0.588...) in order to manipulate them for further calculations.

Edit - as an example, using numpy, I immediately get a real number that I can immediately use:

import numpy as np
np.arctan2(2,3)
0.5880026035475675

So, what is the best way to have the same thing with mpmath?


Solution

  • First, do you realize that numpy functions produce np.float64 values, not 'plain' python floats?

    In [43]: np.atan2(2,3)
    Out[43]: np.float64(0.5880026035475675)
    

    The latest numpy version makes this explicit. On earlier ones you can verify this with type(...).

    With mpmath functions, the return value is mpf/c object, which has all the needed extended precision attributes.

    In [44]: x=mp.atan2(2,3)
    In [46]: x
    Out[46]: mpf('0.5880026035475675')
    

    It's easy to get the equivalent python float:

    In [47]: float(x)
    Out[47]: 0.5880026035475675
    

    To display the mpf value, use:

    In [48]: mp.nstr(x)
    Out[48]: '0.588003'
    

    or with more precision values:

    In [49]: mp.nstr(x,n=30)
    Out[49]: '0.588002603547567503916582154488'
    

    Or as direct print (rather than string):

    In [50]: mp.nprint(x,n=25)
    0.5880026035475675039165822
    

    Similarly for the complex value:

    In [52]: y = mp.loggamma(3+2j)    
    In [53]: y
    Out[53]: mpc(real='-0.031639059373961193', imag='2.022193197501327')
    
    In [54]: complex(y)
    Out[54]: (-0.03163905937396119+2.022193197501327j)
    
    In [55]: mp.nprint(y, n=30)
    (-0.0316390593739611925006016690531 + 2.02219319750132697777189605404j)
    

    To get the two parts separately:

    In [56]: y.real, y.imag
    Out[56]: (mpf('-0.031639059373961193'), mpf('2.022193197501327'))
    

    While nprint is nice for displaying values, you usually don't need to convert things to base python. You can do a lot math directly with the mp objects:

    In [57]: x*y
    Out[57]: mpc(real='-0.018603849285685252', imag='1.1890548650069606')