Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Modify the Matlab Code which uses a \"while\" loop to compute pi to a fixed leve

ID: 3889303 • Letter: M

Question

Modify the Matlab Code which uses a "while" loop to compute pi to a fixed level of precision.

a=0; % the experiment event number
c=0; % sucessful event number
r =1; % redius of the circle
min_tries = 100;

pi_prev = 1000;
precision = 0.00001;

while (true)
    s = 2 * r * (rand() - 0.5); %get a point between -1 to +1
    t = 2 * r * (rand() - 0.5);

    a = a+1;
    pi_sim = 4 * c / a;
    pi_diff = abs(pi_prev - pi_sim);
    pi_prev = pi_sim;

    if (pi_diff <= precision && a>min_tries)
        break;
    end

    if ((s.^2+t.^2)<=r^2)
        c = c+1;
    end
end

fprintf("estimated value of pi is %f", pi_prev);


Modify the code to include four features:

1) FUnction that takes user defined level of precision as input

2) The final computed value of pi, written out to the user-specified precision, should be both displayed in the command window and printed on the plot.

3) The computed value of pi should be returned by the function.

4) A graph that plots the random points as they are made with pts inside the circle in a different color than those outside the circle

Explanation / Answer

a=0; % the experiment event number
c=0; % sucessful event number
r =1; % redius of the circle
min_tries = 100;

pi_prev = 1000;
precision = 0.00001;

while (true)
    s = 2 * r * (rand() - 0.5); %get a point between -1 to +1
    t = 2 * r * (rand() - 0.5);

    a = a+1;
    pi_sim = 4 * c / a;
    pi_diff = abs(pi_prev - pi_sim);
    pi_prev = pi_sim;

    if (pi_diff <= precision && a>min_tries)
        break;
    end

    if ((s.^2+t.^2)<=r^2)
        c = c+1;
    end
end

fprintf("estimated value of pi is %f", pi_prev);

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote