Search code examples
pythonmpmathmultiprecision

python mpmath nstr strip zeros not


How can I let the python mpmath.nstr function keep all the trailing zeros for mpmath.mpf('0')? It looks that the strip_zeros optional argument does not work for mpmath.mpf('0') as seen in the following example:

Python 3.8.5 (default, Jul 28 2020, 12:59:40) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import mpmath
>>> mpmath.dps=30
>>> mpmath.nstr(mpmath.mpf('0'), 10, strip_zeros=False)
'0.0'
>>> mpmath.nstr(mpmath.mpf('1'), 10, strip_zeros=False)
'1.000000000'
>>> 

Solution

  • From the source, it appears that this is by design (https://github.com/fredrik-johansson/mpmath/blob/master/mpmath/libmp/libmpf.py) in to_str():

        # Special numbers
        if not s[1]:
            if s == fzero:
                if dps: t = '0.0'
                else:   t = '.0'
                if show_zero_exponent:
                    t += 'e+0'
                return t
            if s == finf: return '+inf'
            if s == fninf: return '-inf'
            if s == fnan: return 'nan'
            raise ValueError
    

    I don't have an explanation why this would be the case, but considering this is not something wrong with your code, you should probably ask the maintainers of the project for the reason (and perhaps for a way around it, if you require it).