| Show Slide 1
Containing title, name of the production team along with the logo of MHRD
|Hello friends and welcome to the tutorial on 'Least Square Fit'.|
| Show Slide 2
| At the end of this tutorial, you will be able to,
| Show Slide 3
| Before beginning this tutorial,we would suggest you to complete the tutorial on "Using plot interactively", "Loading data from files" and "Getting started with arrays".
Let us start this tutorial with the help of an example.
| Show Slide 4
|Generate a least square fit line for l v/s t^2 using the data in the file 'pendulum.txt'.|
|Open the file 'pendulum.txt' and show|| We have an input file generated from a simple pendulum experiment.
It contains two columns of data. The first column is the length of the pendulum and the second is the corresponding time period of the pendulum.
As we know, the square of time period of a pendulum is directly proportional to its length, we shall plot l vs t^2 and verify this.
To read the input file and parse the data, we are going to use the loadtxt function. Switch to the terminal.
| ipython -pylab
l, t = loadtxt("/home/fossee/pendulum.txt", unpack=True) l t
| We can see that l and t are two sequences containing length and time values correspondingly.
Let us first plot l vs t^2.
| tsq = t * t
plot(l, tsq, 'bo')
Switch to the plot window
| We can see that there is a visible linear trend, but we do not get a straight line connecting them. We shall, therefore, generate a least square fit line.
We will first generate the two matrices tsq and A. Then we will use the lstsq function to find the values of m and c.
| Switch to the terminal
inter_mat = array((l, ones_like(l))) inter_mat
|let us now generate the A matrix with l values. We shall first generate a 2 x 90 matrix with the first row as l values and the second row as ones. Then take the transpose of it. Type|
| A = inter_mat.T
|We see that we have intermediate matrix. Now we need the transpose. Type|
|result = lstsq(A, tsq)||Now we have both the matrices A and tsq. We only need to use the lstsq Type|
| m, c = result
|The result is a sequence of values. The first item in this sequence, is the matrix p i.e., the values of m and c.|
| tsq_fit = m * l + c
plot(l, tsq, 'bo') plot(l, tsq_fit, 'r')
|Now that we have m and c, we need to generate the fitted values of t^2. Type|
|We get the least square fit of l vs t^2.|
| Show Slide 5
| This brings us to the end of the tutorial. In this tutorial, we have learnt to,
| Show Slide 6
Self assessment questions slide
| Here are some self assessment questions for you to solve
| Show Slide 7
Solution of self assessment questions on slide
| And the answers,
Enumerated list ends without a blank line; unexpected unindent.
A = array(u, ones_like(u)).T result = lstsq(A, v) m, c = result lst_line = m * u + c
| Show Slide 8
|Hope you have enjoyed this tutorial and found it useful. Thank you!|