0

I have a question but I do not know what is the relevant part to search or read about.

I would like to calculate some values but Python gives me a rounded value. For example np.exp(3.832781064493026e-31) = 1 but it should not be 1. What is the way of avoiding these approximations? It should be like 1.00000000000000000000000000000384922.

Ma Y
  • 696
  • 8
  • 19
  • 4
    http://floating-point-gui.de – deceze Jan 15 '20 at 13:25
  • 2
    Pretty sure it should not be 8.19991758425e-19... – Kelly Bundy Jan 15 '20 at 13:25
  • @mkrieger1 Indeed I do not understand the solution or answers in that question – Ma Y Jan 15 '20 at 13:29
  • @HeapOverflow Why?! – Ma Y Jan 15 '20 at 13:30
  • e^0 is 1, not 0. – Kelly Bundy Jan 15 '20 at 13:31
  • 1
    There are arbitrary precision libraries like mpmath, and variable precision libraries like decimal, but they cannot act as drop-in replacement for floating point numbers as functions like np.exp or math.exp don't know how to deal with them and instead just try to convert them to floating point again, defeating your purpose. So whichever library you use, you'll have to make sure it implements all the mathematical functions you need – Hymns For Disco Jan 15 '20 at 13:32
  • @JohanC I've seen it but I don't see how it addresses this. Even if they meant 1+8.19991758425e-19, that's still far off the correct value (as your calculation shows). – Kelly Bundy Jan 15 '20 at 14:13

1 Answers1

4

There is mpmath, numpy's multiprecission cousin:

from mpmath import mp
mp.dps = 100
print(mp.exp(3.832781064493026e-31))
# 1.000000000000000000000000000000383278106449302614152558221812007328689735262269801950763925404522797

print(np.expm1(3.832781064493026e-31))
# 3.832781064493026e-31

print(1+np.expm1(3.832781064493026e-31))
# 1.0
# the second term is eaten away by the 64 bit precission (about 16 decimal digits)

Note that mpmath is quite slower than numpy, doesn't work with numpy's arrays and doesn't mix well with other libraries.

Alternatively, especially if you want to calculate exp(x)-1, there is numpy's expm1. This function is introduced because of the precission problems you run into when first calculating exp(x) and then subtracting 1 for small values of x. A better explanation can be found in this post and more thoroughly here.

JohanC
  • 71,591
  • 8
  • 33
  • 66