Pages

mardi 4 février 2014

deal with very small value in python


sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.2204460492503131e-16, radix=2, rounds=1)

1+sys.float_info.epsilon  -----> 1.0000000000000002

1+sys.float_info.epsilon/10  -----> 1.0


To use and compute with very small values in python:

1) use the decimal module:
The defaut precision of decimal is 28, and we can change it. For example to define the Plank constant, 6.62606957e-34, we can do:
import decimal
decimal.getcontext().prec=46
h=decimal.Decimal('6.62606957e-34')
wavelength = np.arange(0.0001, 100)

frequency = c/wavelength
Iv = 5
tb = []
for v in frequency:
    temp_v = decimal.Decimal(str(v))
    temp_tb = h*temp_v/kb/(1+2*h*temp_v**3/Iv/c**2)
    #temp_tb_float = float(temp_tb)
    tb.extend([temp_tb])




Attention:
i) if use decimal, then we can not compute with another number which is defined in numpy.float64 for example. we have to convert them to the same format.
ii) the results of decimal is a string, and we can transfer to float directly.


2) use the C99 concept of nextafter to calculate the value appropriate epsilon. For Python, either use numpy or the Decimal class to calculate nextafter.



Aucun commentaire:

Enregistrer un commentaire