首页 > 编程 > Python > 正文

python 梯度法求解函数极值的实例

2019-11-25 12:27:07
字体:
来源:转载
供稿:网友

如下所示:

#coding utf-8a=0.001    #定义收敛步长xd=1    #定义寻找步长x=0     #定义一个种子x0i=0     #循环迭代次数y=0dic={}import mathdef f(x): y=math.sin(x) #定义函数f(X)=sinx return ydef fd(x): y=math.cos(x) #函数f(x)导数fd(X)=cosx return ywhile y>=0 and y<3.14*4: y=y+xd x=y while abs(fd(x))>0.001: #定义精度为0.001  x=x+a*fd(x) if x>=0 and x<3.14*4:  print(x,f(x))  dic[y]=xprint(dic)ls=[]for i in dic.keys(): cor=0 if ls is None:  ls.append(dic[i]) else:  for j in ls:   if dic[i]-j<0.1:    cor=1    break  if cor==0:   ls.append(dic[i])print(ls)

以上这篇python 梯度法求解函数极值的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表