TASK: Write a script which estimates the average distance between two random points in the unit square, using a FOR loop and the RAND() function.
COMMENT: Given two points (X1,Y1) and (X2,Y2), their distance is found by squaring the distance in the X values, squaring the distance in the Y values, adding these two values and taking the square root.
\begin{align} distance((x1,y1),(x2,y2)) &= \sqrt{(x1-x2)^2+(y1-y2)^2} \end{align} |
Your task is to generate random values of (X1,Y1) and (X2,Y2), and compute the distance D. Do this N times, each time adding the value of D to a total DSUM. Once the computations are done, report the average value of D, which is DSUM/N.
INSTRUCTIONS:
Use "input()" to get a value for N. Initialize DSUM. Your FOR loop runs N times. Set the four values X1, Y1, X2, and Y2 by calling rand(). Compute D, the distance between (x1,y1) and (x2,y2). Add D to DSUM. End your loop Print the final value of DSUM/N
CHECK: Obviously, each D will be a value between 0 and the square root of 2, which is about 1.4. Therefore, a very rough guess for your result might be 0.7, but the answer is between 0.45 and 0.55.
SUBMIT: Your work should be stored in a script file called "hw0091.m". Your script file should begin with at least three comment lines:
% hw0091.m % YOUR NAME % This script (describe what it does) % Add any comments here that you care to make.If this problem is part of an assignment, then submit it to Canvas.