首页 > 解决方案 > python中的优化返回大数的猜测值

问题描述

我想解决python中的优化问题。我的代码如下:

import numpy as np
import math
from scipy.optimize import minimize

def solve(tupleList, a_float, b_float, c_float, *, debug=False, formatStr = '%s'):

    def objective(x, sign= -1.0):
        total = 0
        for xi, pooli in zip(x, tupleList):
            Li, fi = pooli
            total += (xi + Li)*(1 - math.exp((-1)*a_float*b_float*(1-fi)*xi/(xi+Li)))
        total += (c_float - sum(x))*(1 - math.exp((-1)*a_float*b_float))
        total *= sign
        return total

    def constraint1(x, sign= -1.0):
        return sign*(sum(x) - c_float)

    n = len(tupleList)
    x0 = np.ones(n) * c_float/(n+1)  # Initial guess
    if debug:
        print('Initial Objective: {formatStr}'.format(formatStr=formatStr) % objective(x0))

    b = (0,c_float)
    bnds = (b,) * n
    con1 = {'type': 'ineq', 'fun': constraint1} 
    cons = ([con1])
    solution = minimize(objective,x0,method='SLSQP',\
                            bounds=bnds,constraints=cons)  
    x = solution.x

    if debug:
        # show final objective
        print('Final Objective:   {formatStr}'.format(formatStr=formatStr) % objective(x))

        # print solution
        print('Solution')
        for n, xi in enumerate(x):
            print('l_%d    = {formatStr}'.format(formatStr=formatStr) % (n, xi))
        print(    'l_rem = {formatStr}'.format(formatStr=formatStr) % (c_float - sum(x)))   

    if solution.success:
        x = np.append(x,(c_float - sum(x)))
        return x

    return None

如果我按如下方式调用函数,优化似乎工作正常

>>> solve([(8.762E+5, 0.04), (5816E+2, 0.025), (1.5E+2, 0.015)], 7E-05, 103086,1E+0,debug=True)
Initial Objective: -5.507040251221752
Final Objective:   -7.043360870993145
Solution
l_0    = 0.0
l_1    = 0.7846865050106637
l_2    = 0.2153134949835263
l_rem = 5.810019132468369e-12
array([0.00000000e+00, 7.84686505e-01, 2.15313495e-01, 5.81001913e-12])

但是如果我使用更大的数字(我只是将输入乘以 1E+13),那么代码只会返回初始猜测值(在 # Initial guess 行中提供)

>>> solve([(8.762E+18, 0.04), (5816E+15, 0.025), (1.5E+15, 0.015)], 7E-05, 103086,1E+13,debug=True)
Initial Objective: -55070402512217.52
Final Objective:   -55070402512217.52
Solution
l_0    = 2500000000000.0
l_1    = 2500000000000.0
l_2    = 2500000000000.0
l_rem = 2500000000000.0
array([2.5e+12, 2.5e+12, 2.5e+12, 2.5e+12])

有人可以提供一个想法,说明如何让它适用于 1E+18 等大数吗?

标签: pythonpython-3.xnumpyoptimizationscipy

解决方案


推荐阅读