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 – minimizing a function of several variables


Now, we'll minimize a function of two variables, and use a contour plot to illustrate the results:

var('x, y')
f = 100 * (y - x^2)^2 + (1 - x)^2 + 100 * (2 - y^2)^2 + (1 - y)^2
min = minimize(f, [0,0], disp=0)

plt = contour_plot(f, (x, -0.3, 2), (y, -0.3, 2), fill=False,
    cmap='hsv', labels=True)

pt = point(min, color='red', size=50)
show(plt+pt, aspect_ratio=1, figsize=(4, 4))

The plot is shown below:

What just happened?

We started out by defining a callable symbolic expression that represents a polynomial function of two variables. We then used minimize to find a minimum of the function near the point (0,0). minimize works a little differently from the functions in the previous examples. Rather than specifying limits on the domain of the problem, you need to pass an initial guess to minimize so that it knows where to start searching for a minimum. Like the functions find_root and find_minimum_on_interval, minimize will only...