Imagine a square with sides of 2 meter. In the centre is point M, at (0,0). We randomly throw darts at this square, which all hit at some location p on the square (uniform distribution). Next, we count the number of ‘hits’. Each dart is a hit when the distance from p to M is less than or equal to 1.
I have this code I dont know how to count the number of p that is less than or equal to 1
for i=1:100;
p_x= -1+(1+1)*rand;
p_y= -1+(1+1)*rand;
p = sqrt((p_x)^2 + (p_y)^2)
end;

 採用された回答

KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 9 月 22 日
編集済み: KALYAN ACHARJYA 2019 年 9 月 22 日

0 投票

"I have this code I dont know how to count the number of p that is less than or equal to 1"
count=0;
for i=1:100
p_x= -1+(1+1)*rand;
p_y= -1+(1+1)*rand;
p = sqrt((p_x)^2 + (p_y)^2)
if p<=1
count=count+1;
end
end
fprintf('The p count is (when p<=1): %d',count);

1 件のコメント

BMNX
BMNX 2019 年 9 月 22 日
Thank you so much

サインインしてコメントする。

その他の回答 (1 件)

madhan ravi
madhan ravi 2019 年 9 月 22 日

1 投票

N = 100; % no loops needed
p_x= -1+(1+1)*rand(N,1);
p_y= -1+(1+1)*rand(N,1);
p = sqrt(p_x.^2 + p_y.^2);
fprintf('No of times P less than or equal to one:%d',nnz(p<=1))

1 件のコメント

KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 9 月 22 日
Yes @Madhan, I haven't noticed that

サインインしてコメントする。

カテゴリ

ヘルプ センター および File Exchange で Programming についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by