Handling very small numbers in python

I am currently working with very small numbers in my python program, for example.

x = 200 + 2e-26 

One solution is to work with logarithmic values ​​that increase the range of my float value. The problem is that I also need to do fft with these values, and therefore the use of the logarithmic approach is unacceptable (and also use the Decimal module). Is there any other way to solve this problem?

Edit: My problem with Decimal module: how can I handle imaginary values? I tried a = Decimal(1e-26)+Decimal(1e-26*1j) and a = Decimal(1e-26)+Decimal(1e-26)*1j , and both paths failed (error on request).

+8
python
source share
2 answers

Consider the mpmath package example.

 >>> from mpmath import mpf, mpc, mp >>> mp.dps = 40 >>> mpf(200) + mpf(2e-26) + mpc(1j) mpc(real='200.0000000000000000000000000200000000000007', imag='1.0') 

It is mostly accurate and can handle complex numbers, in more detail in the documentation .

+2
source share

While numpy supports more decimal types (as well as complex versions), they do not help:

 >>> import numpy >>> numpy.longfloat <type 'numpy.float128'> >>> 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 : 80 bits are used inside numpy , which means 63 bits of the mantissa, which only supports 63/3 = 21 characters.

You need a real 128-bit float type as one of boost .

Try the Boost.Python module , which can give you access to this type. If this does not work, you will have to write your own wrapper class in C ++, as described here .

+1
source share

All Articles