Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – approximating derivatives with differences


Let's start by defining a function of one variable. We'll use NumPy to estimate the derivative numerically, and we'll plot the estimate with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

import matplotlib as mpl
mpl.rc('font', size=10)      # set default font size
dx = 0.01
x = np.arange(0, 2, dx)
f = power(x, 3)
dfdx = 3*power(x, 2)

plt.figure(figsize=(4, 4))
plt.plot(x, f, label='f(x)')
plt.plot(x, dfdx, color='red', label='Analytical df/dx')

df = np.diff(f)
plt.plot(x[:-1], df/dx, color='black', label='Numerical df/dx')

plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend(loc='best')
plt.savefig('diff.png')
plt.close()

The output is shown in the following screenshot:

What just happened?

We defined a simple polynomial, f(x)=x3. Its derivative can easily be calculated in closed form: f'(x)=3x2. We defined a NumPy array of x values and computed the value of the function at each point. We then used the diff function...