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 – computing gradients


Enter the following code into a cell in a Sage worksheet, and evaluate it:

import numpy as np
import matplotlib.pyplot as plt

def func(x,y):
    return exp(-1 / 3 * x^3 + x - y^2)
    
dx = 0.2; dy = 0.2

grid = np.ogrid[-2 : 2 + dx : dx, -2 : 2 + dx : dx]
xlen = max(grid[0].shape)
ylen = max(grid[1].shape)

f = np.empty([xlen, ylen])
for i in range(xlen):
    for j in range(ylen):
        f[i, j] = func(grid[0][i], grid[1][0,j])
        
plt.figure(figsize=(5, 5))
c = plt.contour(grid[0].flatten(), grid[1].flatten(), f)
plt.clabel(c)         # label contours
plt.axis('scaled')    # aspect ratio=1.0

# Compute and plot gradient of function
grad = np.gradient(f, dx, dy)
plt.quiver(grid[0].flatten(), grid[1].flatten(), grad[0], grad[1])

plt.savefig('contour.png')
plt.close()

A contour plot of the function is shown below, with overlaid vectors representing the gradient:

What just happened?

Computing the gradient is actually the easiest aspect of this example...