import random
'''
drd notes: 使用梯度下降法 求y=3x^2 + 7x - 10波谷时x的值
'''
def my_function(x):
# drd notes:y = 3x^2 + 7x - 10
return 3 * x * x + 7 * x - 10
def my_function_slop(x):
# drd notes: 切线方程对应为y = 6x + 7
return 6 * x + 7
# drd notes:求y最小值时的x
def gradient_descent_min():
# drd notes: 产生随机初始化的点
x0 = random.randint(-100, 100)
w = 0.001
precision = 1e-6
count = 0
# drd notes:一元二次方程经过多次 梯度下降 走法,最后必然会在最小值附近
while True:
x1 = x0 - my_function_slop(x0) * w
count = count + 1
# drd notes: 达到精度后就推出
if abs(my_function(x1) - my_function(x0)) < precision:
break
x0 = x1
# drd notes:波谷点为(-7/6, 169/12), -7/6 = -1.1666666
# drd notes: 经过 1001 迭代后,当x = -1.161392224931042时,y有最小值-14.083249874126466
# 经过 1472 迭代后,当x = -1.1719342628187626时,y有最小值-14.083250090625668
print('经过 {} 迭代后,当x = {}时,y有最小值{}'.format(count, x0, my_function(x0)))
if __name__ == '__main__':
gradient_descent_min()
【Python】梯度下降法求解一元二次函数的波谷
最新推荐文章于 2022-09-16 10:31:10 发布