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 – finding roots


Enter the following code into an input cell in a worksheet, and evaluate the cell:

# A problem we already know the answer to
var('a, b, c, x')
f(x) = a * x^2 + b * x + c
root_list = f.roots(x)
for root in root_list:
    print("Root with multiplicity {0}:".format(root[1]))
    show(root[0])

# Something more complicated
g(x) = expand((x^2 - 1)^3 * (x^2 + 1) * (x - 2));
g.show()
root_list = g.roots(x)
for root in root_list:
    print("Root: {0}  multiplicity: {1}".format(root[0], root[1]))
p1 = plot(g, (-2, 2))
p1.ymin(-10)
p1.show()

The output is shown in the following screenshot:

What just happened?

We started off by finding the roots for the general second-order polynomial with the roots method. The result is a list of tuples that represent the roots. The first item in each tuple is the multiplicity, and the second item is the root. We passed the variable x to roots. If this argument is not provided, roots formulates the solution in terms of the default variable...