Writing a program for generating random numbers involving a circle and a square, help please??

3 次查看(过去 30 天)
A circle of radius 1 is centered in a square target with sides of length 2. The are of the circle to the are of the square is pi/4, so if you throw darts at random, they will have an equal chance of hitting any part of the target. I know that the probability is pi/4, and that pi is 4 times the ratio of: # of throws inside the cirlce (this is divide>) ---------------------------------- total # of throws
What I am trying to accomplish is generating random coordinate pairs (x,y) using x = -1 + 2*rand(n,1)), and plotting pi as a function of the number n of throws by first: throwing 1 dart for the 1st estimate, and throwing 2 darts to get the second, 3 for the third, etc.
I have some coding but a student told me it was all wrong and to try asking on this website. help please!!!
  3 个评论
Reelz
Reelz 2012-4-17
Program is on a school computer, which I won't be able to access for a couple of days. I was trying to create a square matrix with some sort of circulant matrix inside, but got so confused, help please

请先登录,再进行评论。

回答(1 个)

Geoff
Geoff 2012-4-18
You are generating your x- and y-values between -1 and 1, which means you're automatically sampling randomly within the square. That part is fine.
But like Walter suggests, you can just do one dart at a time. That is, you decide the maximum number of throws N you want to do and generate those N co-ordinates only once.
You need an in/out test for your circle and a way to calculate how your pi ratio evolves as the number of throws increases. You will end up with a N-length vector showing (in theory) progressive convergence on pi.
Functions that will help you achieve this are hypot and cumsum.
By the way, get in the habit of posting your code - especially if you think it's wrong. You are more likely to receive help if there's hard evidence that you are also trying to solve it on your own. =)
  11 个评论
Walter Roberson
Walter Roberson 2012-5-1
You write,
% Count fraction of points within 1/2 unit of (1, 1)
frac = sum(r <= 1) / n;
but that code is for counting the fraction within 1 unit of (1,1)
Geoff
Geoff 2012-5-1
What do you mean by "not working at all"? What happens when you run the code? Be more helpful in your description. Why are you computing distance to (1,1)? You have obviously decided to perform the experiment on only one quadrant of the circle/square, so why not centre it at (0,0) to make your code clearer? It makes no difference. Please look up the 'hypot' function in MatLab help. I've suggested it to you at least twice. I notice that your function's return value is 'mycir', but at the bottom where you do the calculation you put it into 'mypi'. The calculation itself looks fine. Works for me. I got pi = 3.14 with just 1000 random numbers.

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by