gpt4 book ai didi

python - 如何使用好 scipy.optimize.fmin

转载 作者:行者123 更新时间:2023-12-01 05:23:27 36 4
gpt4 key购买 nike

您好,我正在尝试使用 scipy.optimize.fmin 来最小化函数。但事情进展不顺利,因为我的计算似乎发散而不是收敛,并且我收到了错误。我尝试修复容差,但不起作用。这是我的代码(主程序):

import sys,os
import numpy as np
from math import exp
import scipy
from scipy.optimize import fmin

from carlo import *

A=real()

x_r=0.11245
x_i=0.14587

#C=A.minim
part_real=0.532
part_imag=1.2
R_0 = fmin(A.minim,[part_real,part_imag],xtol=0.0001)

还有类(class):

import sys,os
import numpy as np
import random, math
import matplotlib.pyplot as plt
import cmath
#import pdb
#pdb.set_trace()

class real:
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2

def minim(self,p):

x_r=p[0]
x_i=p[1]
x=complex(x_r,x_i)
self.a=complex(3,4)*(3*np.exp(1j*self.L_ch))
self.T=np.array([[0.0,2.0*self.a],[(0.00645+(x)**2), 4.3*x**2]])
self.Id=np.array([[1,0],[0,1]])
self.disp=np.linalg.det(self.T-self.Id)
print self.disp
return self.disp

错误是:

(-2.16124712985-8.13819476595j)
/usr/local/lib/python2.7/site-packages/scipy/optimize/optimize.py:438: ComplexWarning: Casting complex values to real discards the imaginary part
fsim[0] = func(x0)
(-1.85751684826-8.95377303768j)
/usr/local/lib/python2.7/site-packages/scipy/optimize/optimize.py:450: ComplexWarning: Casting complex values to real discards the imaginary part
fsim[k + 1] = f
(-2.79592712985-8.13819476595j)
(-3.08484130014-7.36240080015j)
(-3.68788935914-6.62639114029j)
/usr/local/lib/python2.7/site-packages/scipy/optimize/optimize.py:475: ComplexWarning: Casting complex values to real discards the imaginary part
fsim[-1] = fxe
(-2.62046851255e+87-1.45013007728e+88j)
(-4.037931857e+87-2.2345341712e+88j)
(-7.45017628087e+87-4.12282179854e+88j)
(-1.14801242605e+88-6.35293780534e+88j)
(-2.11813751435e+88-1.17214723347e+89j)
Warning: Maximum number of function evaluations has been exceeded.

实际上我不明白为什么计算会发散,也许我必须使用其他东西而不是使用 fmin 来最小化?有人有主意吗?非常感谢。

最佳答案

尝试优化绝对值而不是复数值。这给了我不错的结果。

f = lambda x: abs(A.minim(x))
R_0 = fmin(f,[part_real,part_imag],xtol=0.0001)

我猜 fmin 不能很好地处理复杂的值。

关于python - 如何使用好 scipy.optimize.fmin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21863227/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com