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 the QR factorization


The QR factorization can be used to solve linear least squares problems. The QR factorization decomposes an m x n matrix A (with m≥n) into two matrices called Q and R, such that A=QR. Q is an m x n matrix with orthonormal columns and R is an n x n matrix that is upper triangular and invertible. In this example, we will see how easy it is to compute the QR factorization with Sage.

# This is an example where it's important to specify the correct ring
A = Matrix(RDF, [[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]])
print("Matrix A:")
show(A)
Q, R = A.QR()
print("Matrix with orthonormal basis:")
show(Q)
print("Upper diagonal matrix:")
show(R)
print("Q*R recovers A:")
show(Q*R)

The output should look like this:

What just happened?

We defined a 4 by 3 matrix called A over the ring called RDF, which is a shortcut for RealDoubleField. An RDF object is a double-precision approximation of a floating point number, while a RealField object can have an arbitrary...