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)
Может кто-нибудь дать мне несколько советов?
'Напишите код для расчета первой производной ...' Что вы пробовали до сих пор? Пожалуйста, предоставьте минимальный рабочий пример кода, иначе ваш вопрос будет помечен, если вы его не предоставите. –