# coding: utf-8 import numpy as np import matplotlib.pylab as plt ##数值微分 def numerical_diff(f, x): h = 1e-4 # 0.0001 return (f(x+h) - f(x-h)) / (2*h) def function_1(x): return 0.01*x**2 + 0.1*x ##返回值是一个关于t的函数,以d为斜率 y为截距的函数 def tangent_line(f, x): d = numerical_diff(f, x) print(d) y = f(x) - d*x return lambda t1: d*t1 + y x = np.arange(0.0, 20.0, 0.1) y = function_1(x) plt.xlabel("x") plt.ylabel("f(x)") #function_1在5上的切线 tf = tangent_line(function_1, 5) y2 = tf(x) plt.plot(x, y,"b") ##第一个图,原图0.01*x**2 + 0.1*x plt.plot(x, y2,"r") ##第二个图,红色,表示5这点以这点数值微分为斜率的斜线 plt.show() ##两个图一起展示
关于梯度计算(实际上用数值微分近似计算)
最新推荐文章于 2024-08-13 17:04:59 发布