Handling very small numbers in python

前端 未结 2 1765
故里飘歌
故里飘歌 2021-02-14 17:56

I am currently working with very small numbers in my python program, e.g.

x = 200 + 2e-26

One solution is to work with logarithmic values whic

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-14 18:18

    While numpy supports more decimal types (and also complex versions), they don't help:

    >>> import numpy
    >>> numpy.longfloat
    
    >>> a = numpy.array([200, 2e-26], dtype=numpy.longfloat)
    >>> a
    array([ 200.0,  2e-26], dtype=float128)
    >>> a.sum()
    200.0
    >>> a = numpy.array([200, 2e-26], dtype=numpy.longdouble)
    >>> a.sum()
    200.0
    

    The reason is explained here: Internally, numpy uses 80 bits which means 63 bits mantissa which just supports 63/3 = 21 digits.

    What you need is a real 128bit float type like the one from boost.

    Try the Boost.Python module which might give you access to this type. If that doesn't work, then you'll have to write your own wrapper class in C++ as explained here.

提交回复
热议问题