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: