如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#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) |
以上这篇python 梯度法求解函数极值的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_42733218/article/details/81119880