网络编程
位置:首页>> 网络编程>> Python编程>> python 梯度法求解函数极值的实例

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

作者:咚咚怪  发布时间:2023-08-11 07:33:05 

标签:python,梯度,函数,极值

如下所示:


#coding utf-8
a=0.001    #定义收敛步长
xd=1    #定义寻找步长
x=0     #定义一个种子x0
i=0     #循环迭代次数
y=0
dic={}
import math
def f(x):
y=math.sin(x) #定义函数f(X)=sinx
return y
def fd(x):
y=math.cos(x) #函数f(x)导数fd(X)=cosx
return y
while 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]=x
print(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)

来源:https://blog.csdn.net/weixin_42733218/article/details/81119880

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com