2015-04-27 3 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, Л = 1) ^ SyntaxError: неверный синтаксис – penny

Смежные вопросы