Q:

Python overflow when calculating Gaussian function

I am trying to calculate the value of the Gaussian function using the following definition
from math import e

def function(x):
    return 100 / (e**((x-2000)**2))**1/16

But I am getting an overflow with values of 20000, 30000, 1000000, etc.
Do you know a workaround
Thanks!

A:

Use math.exp:
100 / math.exp((x-2000)**2))**1/16

This is more performant and numerically accurate than e**.
Note that ...**1/16 probably doesn't do what you want. ** has higher operator precedence than /, so the above is equivalent to (...**1)/16. Wrap the fraction in parentheses:
100 / math.exp((x-2000)**2)**(1/16.0)

Writing 16 in floating point format (16.0) to prevent integer division.
Use exponent rules to incorporate the 1/16:
100 / math.exp((x-2000)**2/16.0)

This reduces large arguments, which helps to improve precision. 
Flip the sign of the argument and change the division to a multiplication:
100 * math.exp(-(x-2000)**2/16.0)

This will underflow instead of overflow in extreme cases. Underflows are much more well-behaved in this situation – you'll just get zero instead of an OverflowError.

