2015-04-27 69 views
-4

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) at x=0 with h=1 , 0.1, 0.01 and 0.001 . Also compare the result with cos(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 of cos(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) 

誰能給我一些建議嗎?

+1

'編寫一段代碼來計算一階導數......'到目前爲止你嘗試了什麼?請提供最少的工作示例代碼,否則您的問題將被標記爲不提供一個。 –

回答

0

你的主要問題是你除以2 * h,這意味着除以2,然後乘以h。你需要除以(2 * h)。你可能在學校學到了BODMAS rules

>>> 12/2 * 3 
18 

即共分12 2就得到如圖6所示,然後乘以6由3.如果組使用括號(2 * 3),整個乘法操作將被首先評估:

>>> 12/(2 * 3) 
2 

固定碼:

def f_dash(f, x, h): 
    return (f(x + h) - f(x - h))/(2 * h) 

>>> from math import sin, cos 
>>> f_dash(f=sin, x=0, h=0.1) 
0.9983341664682815 

>>> f_dash(sin, 0, 0.001) 
0.9999998333333416 
+0

非常感謝你 – penny

+0

@penny用的什麼是錯的 –

+0

文件 「./55.py」 的解釋,5號線 高清衍生物(0,H = 1) ^ 的SyntaxError更新:無效的語法 – penny