How to calculate exp(x) for really big integers in Python? How to calculate exp(x) for really big integers in Python? numpy numpy

How to calculate exp(x) for really big integers in Python?


The regular python math and numpy modules will overflow on exp(300000).

What you need is an arbitrary precision floating point library.

Prereq: pip install mpmath

from mpmath import *mp.dps=300print exp(300000)2.21090954962043147554031964344003334958746533182776533253160702399084245726328190320934903726540800347936047182773804396858994958295396516475277561815722954583856797032504775443385287094864178178111231967140927970972263439977028621274619241097429676587262948251263990280758512853239132411057394977398e+130288

see also http://code.google.com/p/mpmath/


@Paul already gave you the answer for computational question

However - from neural network point of view your problem is indication that you are doing something wrong. There is no reasonable use of neural networks, where you have to compute such number. You seem to forget about at least one of:

  • Input data scaling/normalization/standarization
  • small weights bounds initizlization
  • regularization term which keeps weights small when the size of network grows

all these elements are basic and crucial parts of working with neural networks. I recommend to have a look at Neural Networks and Learning Machines by Haykin.


decimal module from stdlib allows to compute exp(-300000) with desired precision:

>>> import decimal>>> decimal.getcontext().prec = 300>>> decimal.Decimal(-300000).exp()Decimal('4.52302537736869338168154543856941208987901785730658877589102779454404342316583413710153707357620016787644963947448152347606024065141665176979995260298156742722510150887341893137830615617098803353373668680329179329422367091094657806579661636984526349130940466600671093389647604708034230900336526970689E-130289')

I agree with @lejlot' answer: if you need it then there is something wrong with your neural networks.