Finite difference is a numerical method to approximate a derivative. There are mainly three types of finite difference method: central, forward and backward.衍生2.7
In this question, I will introduce central difference method. we can approximate
f '(x)
by:f'(x)=(f(x+h)-f(x-h))/2h
. Write a code to calculate the first derivative of sin(x) atx=0
withh=1
,0.1, 0.01 and 0.001
. Also compare the result withcos(0)
(to use function 「cos()」, you should import 「math」 first).Draw a graph to compare the result of different h value, x axis is the value of h and y1 axis is the calculated first derivative of
sin(x)
and y2 is the result ofcos(0)
.
#!/usr/bin/env python
import math
def f(x):
return sin(x)
def derivative(0,h=1)
deriv = (f(x + h) - f(x - h))/ 2 * h
return round(deriv, 0)
print "f'(x)=", derivative(0)
誰能給我一些建議嗎?
'編寫一段代碼來計算一階導數......'到目前爲止你嘗試了什麼?請提供最少的工作示例代碼,否則您的問題將被標記爲不提供一個。 –