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 one variable


We'll define another function of one variable and let Sage find the minimum:

var('x')
f = lambda x: 3 * x^3 - 7 * x^2 + 2

minval, x_min = find_minimum_on_interval(f, 0, 3)
print("Min on interval [0,3]: f({0}) = {1}".format(x_min, minval))

maxval, x_max = find_maximum_on_interval(f, -1, 1)
print("Max on interval [-1,1]: f({0}) = {1}".format(x_max, maxval))

f_plot = plot(f, (x, -1, 2.5))
min_point = point((x_min, minval), color='red', size=50)
max_point = point((x_max, maxval), color='black', size=50)
show(f_plot + min_point + max_point, figsize=(4, 4))

The results are shown in the following screenshot:

What just happened?

We defined a function that represents a cubic polynomial using the lambda construct. Recall from Chapter 4 that lambda is a shorthand way of defining a Python function. We used a Python function, rather than a callable symbolic expression, because numerical methods are designed to work with functions that return real...