-4

Finite difference is a numerical method to approximate a derivative. There are mainly three types of finite difference method: central, forward and backward.

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)

Can anyone give me some suggestions?

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
penny
  • 7
  • 2
  • 1
    `Write a code to calculate the first derivative...` What have you tried so far? Please provide a minimal working sample code, else your question will be flagged for not providing one. – ρss Apr 27 '15 at 08:11

1 Answers1

0

Your main problem is you are dividing by 2 * h, this means divide by 2, then multiply by h. You need to divide by (2 * h). You might have learned the BODMAS rules in school.

>>> 12 / 2 * 3
18

That divides 12 by 2 to get 6, then multiplies 6 by 3. If you group (2 * 3) using parentheses, the whole multiplication operation will be evaluated first:

>>> 12 / (2 * 3)
2

Fixed code:

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
Community
  • 1
  • 1
Peter Wood
  • 23,859
  • 5
  • 60
  • 99