python - 如何在任意点绘制抛物线的斜率(切线)?
问题描述
我想绘制一个使用导数来找出函数在任何点的斜率的简单说明。它看起来像这样:
我已经使用以下代码绘制了一个简单的抛物线:
import numpy as np
from matplotlib import pyplot as plt
inputs = 0.2
weights = np.arange(-6,14)
target_prediction = 0.7
prediction = inputs*weights
errors = (prediction - target_prediction) ** 2
plt.xlabel("Weight")
plt.ylabel("Error")
plt.plot(weights, error)
现在我想添加这样的东西:
current_weight = 5
# draw a short fraction of a line to represent slope
x = np.arange(optimal_weight - 3, optimal_weight + 3)
# derivative
slope = 2 * (inputs*current_weight - target_prediction)
y = slope*x # How should this equation look like?
plt.plot(x, y)
画一条穿过 的切线current_weight
。
但我似乎无法弄清楚这一点,你能帮忙吗?
解决方案
一旦在所需点获得斜率,您需要使用点斜率形式编写切线方程:
# Define parabola
def f(x):
return x**2
# Define parabola derivative
def slope(x):
return 2*x
# Define x data range for parabola
x = np.linspace(-5,5,100)
# Choose point to plot tangent line
x1 = -3
y1 = f(x1)
# Define tangent line
# y = m*(x - x1) + y1
def line(x, x1, y1):
return slope(x1)*(x - x1) + y1
# Define x data range for tangent line
xrange = np.linspace(x1-1, x1+1, 10)
# Plot the figure
plt.figure()
plt.plot(x, f(x))
plt.scatter(x1, y1, color='C1', s=50)
plt.plot(xrange, line(xrange, x1, y1), 'C1--', linewidth = 2)
您可以对任何可微函数执行此操作,并且可以使用导数逼近方法(例如有限差分)来消除提供解析导数的需要。
推荐阅读
- javascript - 如何使用 Top.gg SDK 获取选民资料
- facebook-graph-api - Facebook 广告 API 访问令牌
- jmeter - JMeter - 平均响应时间失败的交易账户
- javascript - 如何在 Idea / WebStorm IDE 上运行 HackerRank 的 JavaScript 解决方案?
- wordpress - 在 redux 框架中,multi_text 和幻灯片不起作用
- javascript - 无论 nuxt.config.js 中的什么内容,“If”中的条件模块 require 仍然执行?
- google-sheets - 基于交易列表构建投资组合跟踪器字符:公式/方法不正确
- c++ - SIGABRT 在临界区模拟 C++ 代码
- azure - 如何在 Azure Application Insights 中使用 BeginScope(在 https://portal.azure.com 中)?
- jenkins - 如何在詹金斯中运行ui5命令