溢出错误:数学范围错误指数Python

2024-05-16 08:00:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用python创建一个简单的模拟退火搜索,但是在使用数学实验一

这是我用python编写的代码:

import random
import math

def getF(x1, x2):
    t1 = (4 - (2.1 * (x1 ** 2) + (x1 ** 4) / 3)) * (x1 ** 2)
    t2 = x1 * x2
    t3 = (-4 + (4 * (x2 ** 2))) * (x2 ** 2)
    t = t1 + t2 + t3
    return t


def getP(dE, t):
    return math.exp((-1*dE)/t)


def getNewRandInRange(x):
    newX = x + random.randint(-5, 5)
    while (newX > 10) or (newX < -10):
        newX = x + random.randint(-5, 5)
    return newX

initState1 = random.randint(-10, 10)
initState2 = random.randint(-10, 10)

currentState1 = initState1
currentState2 = initState2

BSF = getF(currentState1, currentState2)

T = 1000
Tmin = 1

while T > Tmin:
    print("T= %f" %T)
    newState1 = getNewRandInRange(currentState1)
    newState2 = getNewRandInRange(currentState2)

    currentF = getF(currentState1, currentState2)
    newF = getF(newState1, newState2)

    print("Current X1= %f" % currentState1)
    print("Current X2= %f" % currentState2)
    print("New X1= %f" % newState1)
    print("New X2= %f" % newState2)

    dE = currentF - newF
    print ("delta E: %f" %dE)

    if dE > 0:
        currentState1 = newState1
        currentState2 = newState2
        BSF = getF(newState1, newState2)
    else:
        randNumber = random.uniform(0, 1)
        p = getP(dE, T)
        if (randNumber < p):
            currentState1 = newState1
            currentState2 = newState2

    print("BSF: %f" %BSF)
    print("\n\n\n")
    T = T * 0.9

print(BSF) #final output

错误消息:

^{pr2}$

我正在尝试使用try-and-catch,但它不会返回指数,这会对结果造成问题,而且我正在尝试google搜索,但没有找到任何符合我要求的解决方案。在

谢谢你之前!在


Tags: returndefderandomprintx1x2randint
1条回答
网友
1楼 · 发布于 2024-05-16 08:00:31

exception OverflowError

当算术运算的结果太大而无法表示时引发。对于长整数(它宁愿引发MemoryError而不是放弃)和大多数使用普通整数的操作(它们返回长整数)都不会发生这种情况。由于C语言中浮点异常处理缺乏标准化,大多数浮点操作也不会被检查。 Ref

你试图计算一个大数(大于710),但这超出了双精度的范围。在

您可以用try/except这样处理它:

def getP(dE, t):
    try:
        return math.exp((-1*dE)/t)
    except:
        return -1 # or anything else :D

您可以在Python的代码中找到以下注释:

^{pr2}$

无论如何,您可以使用Decimal

import decimal
...
def getP(dE, t):
    return decimal.Decimal((-1*dE)/t).exp()

相关问题 更多 >