Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling very small numbers in python

Tags:

python

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 which would increase the range of my float value. The problem is that I have to do a fft with these values, too, and therefore using the logarithmic approach is not usable (and using the Decimal-module neither). Is there another way to solve that problem?

Edit: My problem with the decimal module is: 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 ways failed (error on request).

like image 408
arc_lupus Avatar asked Apr 07 '15 09:04

arc_lupus


People also ask

How do you round small numbers in Python?

Python has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.

What is the smallest number that can be represented in Python?

Simply speaking it gives you some information about rounding errors. The minimum value of 2.2250738585072014e-308 is a normal representation float value. You can get down to about 5e-324 with subnormal representation.

How precise are Python floats?

Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.


1 Answers

Consider trying out the mpmath package.

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

Mostly accurate and can handle complex numbers, more details in the documentation.

like image 113
metatoaster Avatar answered Oct 07 '22 14:10

metatoaster