How to get python to deal with very small numbers?

88 views Asked by At

I am doing a simulated annealing analysis of a travelling salesmen problem, I keep running in to the error:

ZeroDivisionError: float division by zero

I am not dividing by 0, but I am dividing by a value very close to it, but I do not want python to assume that it is 0, I want it to actually perform the calculation, even it it takes a long time.

Here is a snippet of my code where the error is occurring, temperature is the value which is getting very close to 0.

def probability(d_new, d_old, temperature):
    delta = d_new - d_old
    if d_new - d_old >= 0:
        probability = (math.e) ** - (delta/temperature)
    else:
        probability = 1
    return probability

I am using Jupyter Notebooks to run Python, but I am not sure if this makes any difference.

1

There are 1 answers

0
Martin Wettstein On

To prevent errors, you need to include both temperature and delta in the if statement.

def probability(d_new, d_old, temperature):
delta = d_new - d_old
if d_new - d_old >= 0 and temperature > 0:
    probability = (math.e) ** - (delta/temperature)
else:
    probability = 1
return probability