如何让Python处理非常小的数字?

问题描述 投票:0回答:1

我正在对旅行推销员问题进行模拟退火分析,我不断遇到错误:

ZeroDivisionError: float division by zero

我不是除以0,而是除以一个非常接近它的值,但我不希望python假设它是0,我希望它实际执行计算,即使它需要很长时间。

这是我的代码片段,其中发生了错误,

temperature
是非常接近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

我正在使用 Jupyter Notebooks 来运行 python,但我不确定这是否有什么区别?

python traveling-salesman simulated-annealing
1个回答
0
投票

为了防止错误,您需要在 if 语句中包含温度和 Delta。

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
© www.soinside.com 2019 - 2024. All rights reserved.