|
楼主 |
发表于 2021-12-6 12:30:50
|
显示全部楼层
import numpy as np
import matplotlib.pyplot as plt
#numerical derivative of sin(x)
def f(x):
y=exp(x)
return y
def g(x):
y=x**3+7*x**2+5*x
return y
def sigmoid(x):
return np.f(g(x))
N=30 #no. of grids
a=0
b=5
h=(b-a)/(N-1)
x=np.zeros(N)
f=np.zeros(N)
df=np.zeros(N)
df0=np.zeros(N)
for i in range(N):
x[i]=i*h
f[i]=sigmoid(x[i])
df0[i]=np.f(g(x[i]))
if i==1:
#forward difference
df[i]=(sigmoid(x[i]+h)-sigmoid(x[i]))/h
elif i==N-1:
#backward difference
df[i]=(sigmoid(x[i])-sigmoid(x[i]-h))/h
elif i==2:
#central difference
df[i]=(sigmoid(x[i]+h)-sigmoid(x[i]-h))/(2*h)
elif i==N-2:
#central difference
df[i]=(sigmoid(x[i]+h)-sigmoid(x[i]-h))/(2*h)
else:
#5 point formula
df[i]=(sigmoid(x[i]-2*h)-8*sigmoid(x[i]-h)+
8*sigmoid(x[i]+h)-fsigmoid(x[i]+2*h))/(12*h)
plt.plot(x,f,'b',label='f(g(x)')
plt.plot(x,df,'r',label='d(f(g(x))/dx')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.savefig('复合函数.png')
plt.show() |
|