Estimate the Value of Pi

42 Ansichten (letzte 30 Tage)
Yiting Jin
Yiting Jin am 13 Okt. 2021
Bearbeitet: Jan am 13 Okt. 2021
I have written my code for this question. But my teacher says that index a is not supposed to be assigned to d. But I don't know where esle I can assgned it to.
My code passed all test withou any issue.
Down below is my finshed code.
function Pi = estimPi(n)
r = 1; % radius
x = rand(n,1); %is a n-by-1 column vector. All the values in are in the open interval (0, 1).
y = rand(n,1);
noPointsInCircle = 0;
%Start
% input the function used to calculate point distance
d = sqrt(x.^2 + y.^2);
% first, check if the number input is less than 100. If that's the case, pi can't be estmate because the point inputs is too small. In this case, output can't perform estimate for notification.
if n < 100
Pi = ("Can't perform estimate");
return % return control to the invoking program before it reaches the end of the script or function. So next time if it is over 100, the program can be perform.
end
% create a loop to find how many points are in the circle
for a = 1:n % create a 1-by-n column vector. This value is used to test wherether the point is in circle.
if d(a) < r % makes sure the point is inside the circle
noPointsInCircle = noPointsInCircle + 1; %by the end of the loop, the value of noPointsInCirle will be all point in circle.
end
end
Pi = 4 * (noPointsInCircle/n) % input function used to calculate the pi value base on the amount of points in circle
%End
end
  1 Kommentar
Mitchell Thurston
Mitchell Thurston am 13 Okt. 2021
Bearbeitet: Mitchell Thurston am 13 Okt. 2021
It doesn't look like it's being assigned to d? Only that it's being used as the index
All I can think is they would want you to aboid using the loop altogether, which you can do with boolean math. It's a lot neater and more effecient at compilation, so it's better practice, but it's weird to be docked on for an assignment.
You can replace the "for a = ..." until the end of the code with this line (and also get rid of "noPointsInCircle")
Pi = 4 * ( sum(d < r) );

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 13 Okt. 2021
Bearbeitet: Jan am 13 Okt. 2021
Your code runs fine and it is clean. It can be simplified, but the application of the index a is valid. I'm not sure why your teacher sees a problem.
A faster version:
if n < 100 % Prefer error() to catch errors, not strange outputs
Pi = "Can't perform estimate";
return
end
r = 1;
x = rand(n, 1);
y = rand(n, 1);
d = (x.^2 + y.^2); % SQRT can be omitted: sqrt(x) < r if and only if x < r^2
noPointsInCircle = sum(d < r^2);
Pi = 4 * (noPointsInCircle/n)
d < r^2 is a logical vector. The TRUE is treated as 1, the FALSE as 0. So the sum does exactly what your FOR loop does, but much faster.

Weitere Antworten (0)

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by