## Monday, November 21, 2011

### HP 15C Programming Tutorial - Part 9: Derivatives

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		Key001	42	21	12	LBL B002		44	2	STO 2	* stores h003			33	R ↓ 004		44	1	STO 1	* stores X005			2	2	* first term calculation006	45	20	2	RCL × 2007			30	-008		32	0	GSB 0	* f(x - 2h)009		44	0	STO 0	010		45	1	RCL 1011	45	30	2	RCL- 2012		32	0	GSB 0013			8	8014			16	CHS015			20	×	* -8 * f(x - h)016	44	40	0	STO+ 0	017		45	1	RCL 1018	45	40	2	RCL+ 2019		32	0	GSB 0020			8	8021			20	× 	* 8 * (f + h)022	44	40	0	STO+ 0023		45	1	RCL 1024			2	2025	45	20	2	RCL	× 2026			40	+027		32	0	GSB 0028			16	CHS * -f(x + h)029	44	40	0	STO+ 0030		45	0	RCL 0031	45	10	2	RCL÷ 2032			1	1033			2	2034			10	÷035		44	0	STO 0036		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		Key001	42	21	0	LBL 0002			36	ENTER003			12	e^x004			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		Key001	42	21	0	LBL 0002			36	ENTER003			36 	ENTER004			2	2005			30	-006			20	× 007			3	3008			30	-009			16	CHS010		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