本文主要是介绍导数应用(一):差分计算(导数),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
导数应用(一):差分计算(导数)
- 1.数学背景
- 2.代码
1.数学背景
导数: d y d x = y ( x i ) − y ( x i − 1 ) x i − x x − i \frac{dy}{dx} = \frac{y(x_i) - y(x_{i-1})}{x_i - x_{x-i}} dxdy=xi−xx−iy(xi)−y(xi−1)
差分: Δ Y Δ X = Y i − Y i − 1 X i − X i − 1 \frac{\Delta Y}{\Delta X} = \frac{Y_i- Y_{i-1}}{X_i - X_{i-1}} ΔXΔY=Xi−Xi−1Yi−Yi−1
然而由于数据特性,大多数情况 Δ X \Delta X ΔX 远远无法逼近 d x dx dx
由此衍生出各种差分形式,但主要思想万变不离其宗
2.代码
按照惯例,先放图:
- 蓝色曲线为 y 1 = s i n ( x ) y_1 = sin(x) y1=sin(x)
- 黄色曲线为 y 2 = ( s i n ( x ) ) ′ = c o s ( x ) y_2 = (sin(x))' = cos(x) y2=(sin(x))′=cos(x)
- 红色曲线为 y 3 = ( s i n ( x ) ) ′ ′ = − s i n ( x ) y_3 = (sin(x))'' = -sin(x) y3=(sin(x))′′=−sin(x)
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np# 一阶中心差分
def diff_1st_mid(series,dx):arr = []for i in range(0,len(series),1):if i ==0:arr.append((series[1] - series[0])/dx)elif i== len(series)-1:arr.append((series[len(series)-1] - series[len(series)-2])/dx)else:arr.append((series[i+1] - series[i-1])/ (2 * dx) )return arr# 二阶中心差分
def diff_2nd_mid(series,dx):arr = []dx2 = dx * dxfor i in range(0,len(series),1):if i ==0:arr.append((series[2] -2*series[1] + series[0])/dx2)elif i== len(series)-1:arr.append((series[len(series)-1] - 2*series[len(series)-2] +series[len(series)-3])/dx2)else:arr.append((series[i+1] - 2 *series[i] + series[i-1])/ (dx2) )return arrX=np.linspace(-np.pi,np.pi,1000,endpoint=True)Y = np.sin(X)
Diff1 = np.cos(X)DD1 = diff_1st_mid(Y,np.pi * 2 /(len(X)))
DD2 = diff_2nd_mid(Y,np.pi * 2 /(len(X)))plt.plot(X,Y)plt.plot(X,DD1, color = 'yellow', linewidth=1, linestyle="--")
plt.plot(X,DD2, color = 'red', linewidth=1, linestyle="--")print(DD1)plt.show()
这篇关于导数应用(一):差分计算(导数)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!