通过梯度下降找最小函数值

import random


def fun(x):
    return x ** 2 + 3 * x + 5


def derivative(x):
    return 2 * x + 3


if __name__ == '__main__':
    x = random.randint(0, 50)
    learn_rate = 0.01
    while True:
        temp_value = derivative(x)
        if abs(temp_value) < 0.000001:
            break

        if temp_value > 0:
            change_value = -temp_value * learn_rate
        else:
            change_value = temp_value * learn_rate
        x += change_value
        print(f'x:{x},min_value:{fun(x)}')

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。