Cogsci 109 Assignment 4
Deadline extended
Due Thursday November 10, 11:59pm
1. Monte-Carlo Simulations
One use of computers in computational models and data analysis
is to randomly simulate the behavior of a physical or mathematical
system that might be hard to compute exactly ( see for much more on this topic)
In the first question, you will write Matlab programs to estimate the
value of pi. Keeping in mind that the area of a circle of radius r is
pi*r*r and the area of a square that just encloses the circle is
2r*2r=4*r*r, one can estimate the value of pi by uniformly and
randomly generating points from a square of width 2r and seeing what
fraction fall in the enclosed circle.
consider a circle inside a square (just touching the edges as
I drew on the board)
The circle has radius r, so the square as width 2r
Area of a circle = pi * r^2
Area of square = 4*r^2
If you uniformly randomly generate points in the square and see which fall
in the circle you have the following relationship (keeping in mind that
uniformly means proportion to area)
# in circle
----------
# in square
is approximately equal to
area circle
------------
area square
which is equal to
pi
---
4
Therfore pi can be approx by
4*# in circle
------------
# in square
You might want to make r=.5 and look at the following matlab commands:
rand
a) First write a program that loops 1000000 times, each time drawing two
random numbers. Save this program in a file piloop.m
b) Now improve the speed of the program by removing the loop. Save this
program in a file pinoloop.m You might want to look at the following
matlab commands/operators: find .^2
2. Linear Regression
For this question you will use the data files:
xdata
ydata
xdata holds the x-coordinates of a set of data and ydata holds
the corresponding y-coordinates. You might want to look
at the matlab command : load
Put the following code in a script file called regression.m
a) write the code to plot the 2-dimensional data as green stars.
b) write the code to fit the best (in the least squares sense) linear
fit to the data.
c) write the code to draw this on the graph of the data as a red line.
d) write the code to fit the best fifth order fit to the data and draw
this on the graph of the data as a black curve. Which looks like a better
fit to you? Next homework we will see one way to quantify this.
What to Hand In
Hand in your script files piloop.m, pinoloop.m and your script file regression.m, using the
turnin program. There is no need to hand in graphs.