python - 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 等大数吗?
解决方案
推荐阅读
- java - 当我尝试使用 Freemarker Spring Boot 删除元素时出现异常 505
- python - python3x TypeError:'dict_keys'
- python - 在 Django 中解压的值太多(预期为 2)
- jsf - p:blockUI 从数据表触发时未显示
- javascript - 反应状态更新
- flutter - Flutter -PDF -- 错误 - 这个小部件创建了 20 多个页面。这可能是小部件或文档中的问题
- javascript - 从索引中获取索引
- javascript - jquery .css() 方法在添加或删除任何字符之前不起作用
- python - 使用 matplotlib 绘制熊猫数据框,数据按年/月分组
- kubernetes - Kubernetes 中的网络策略问题