How to handle functions with division by zero

849 views Asked by At

I'm trying to employ some models using python / numpy of the form:

 f(x) = 1 / (exp(x) - 1)

where x can be any value from -5 to +5 say.

x can be zero and during my simulations this does occur, causing f(x) to tend to infinity, which returns a nan + 1jnan.

Since I then want to use the results from this calculation later on, e.g. to FFT, this creates a major problem, since the fft routine can't handle NANs in the input.

Are there any recommended ways of dealing with this please? e.g. putting logic to say: if x == 0: return 0 or e.g. shifting x by 0.00000001% if it equals zero, to avoid this problem.

Thanks

1

There are 1 answers

0
shley On BEST ANSWER

You can simply avoid this problem by using a continue statement:

def f(x):
    return 1 / (exp(x) - 1)

f_values = {}
for i in range(-5,5):
    if i == 0: continue
    f_values[i] = f(i)

print f_values
>>> {1: 0.5819767068693265, 2: 0.15651764274966565, 3: 0.05239569649125595, 4: 0.01865736036377405, -2: -1.1565176427496657, -5: -1.0067836549063043, -4: -1.018657360363774, -3: -1.052395696491256, -1: -1.5819767068693265}


FFT(f_values)

Here, whenever the value of x = 0 occurs, the loop simply avoids the f(x) function and iterates to the next value.