**Numerical Derivatives**

In Part 9, we will calculate numerical derivatives of f(x). Computing accurate numerical derivatives can present a challenge. Often, calculation involves a small increment, usually named *h*. Generally, the smaller *h* is, the better the calculation. However with certain methods, if *h* is too small, the final result may be unexpected.

This program uses a five-point formula:

f'(x) ≈ (f(x - 2h) - 8 * f(x - h) + 8 * f(x + h) - f(x + 2h)) / (12h)

The error is of the order of h^4.

Source: Burden, Richard L. and J. Douglas Faires. "Numerical Analysis 8th Edition" Thomson Brooks/Cole Belton, CA 2005

Labels Used:

Label B: Main routine

Label 0: The function f(R1). The function starts with R1 loaded on the X register.

Memory Registers Used:

R0 = the numerical derivative

R1 = X

R2 = h

Program Listing

Key Codes Key

001 42 21 12 LBL B

002 44 2 STO 2 * stores h

003 33 R ↓

004 44 1 STO 1 * stores X

005 2 2 * first term calculation

006 45 20 2 RCL × 2

007 30 -

008 32 0 GSB 0 * f(x - 2h)

009 44 0 STO 0

010 45 1 RCL 1

011 45 30 2 RCL- 2

012 32 0 GSB 0

013 8 8

014 16 CHS

015 20 × * -8 * f(x - h)

016 44 40 0 STO+ 0

017 45 1 RCL 1

018 45 40 2 RCL+ 2

019 32 0 GSB 0

020 8 8

021 20 × * 8 * (f + h)

022 44 40 0 STO+ 0

023 45 1 RCL 1

024 2 2

025 45 20 2 RCL × 2

026 40 +

027 32 0 GSB 0

028 16 CHS * -f(x + h)

029 44 40 0 STO+ 0

030 45 0 RCL 0

031 45 10 2 RCL÷ 2

032 1 1

033 2 2

034 10 ÷

035 44 0 STO 0

036 43 32 RTN

Instructions:

1. Enter the main program (Label B).

2. Enter the function f(R1) (Label 0).

3. Enter X, press [ENTER].

4. Enter h, press [ f ] [e^x] (B).

5. The approximate numerical derivative is displayed.

Caution: Remember to end the function with the RTN command ([ g ] [GSB] (RTN)).

Example 1

Let f(x) = x*e^x

Estimate f'(2) with h = 0.0001

Key Code Key

001 42 21 0 LBL 0

002 36 ENTER

003 12 e^x

004 20 ×

005 43 32 RTN

To find the derivative:

Press 2 [ENTER] .0001 [ f ] [e^x] (B)

Result: f(2) ≈ 22.1672

Example 2

Let f(x) = -x^2 + 2x + 3

Estimate f'(1.5) with h = 0.0001

We can rewrite f(x) as:

f(x) = -x^2 + 2x + 3

-1 * (x^2 - 2x - 3)

-1 * (x * (x - 2) - 3)

Use the last form as the function.

Key Code Key

001 42 21 0 LBL 0

002 36 ENTER

003 36 ENTER

004 2 2

005 30 -

006 20 ×

007 3 3

008 30 -

009 16 CHS

010 43 32 RTN

To find the derivative:

1.5 [ENTER] .0001 [ f ] [e^x] (B)

Result: f'(1.5) ≈ -1

Next time, we will look at how we can use statistics in programming. Until next time, happy programming,

Eddie

*This tutorial is property of Edward Shore. © 2011*