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 – least squares fitting


The following is adapted from an example in the Sage documentation:

var('a, b, c, x')
set_random_seed(0.0)
data = [(i, 1.2 * sin(0.5 * i - 0.2) + 0.1 *
    normalvariate(0, 1)) for i in xsrange(0, 4 * pi, 0.2)]
data_plot = list_plot(data)

model(x) = a * sin(b * x - c)

fitted_params = find_fit(data, model, solution_dict=True)
print("a = {0}".format(fitted_params[a]))
print("b = {0}".format(fitted_params[b]))
print("c = {0}".format(fitted_params[c]))

g(x) = model.subs(a=fitted_params[a], b=fitted_params[b], c=fitted_params[c])
fitted_plot = plot(g(x), (x, 0, 4 * pi), color='red')
show(data_plot + fitted_plot, figsize=(4, 3))

The noisy data, and the fitted function, are shown below:

What just happened?

After declaring some symbolic variables, we called the set_random_seed function to fix the seed for the pseudo-random number generator. A pseudo-random number generator will always generate the same sequence of numbers for a given seed value. Setting the...