Monte Carlo Simulation question?
2 次查看(过去 30 天)
显示 更早的评论
Hey, I need to make a program that proves monte carlo sampling to find the area of a circle. So basically, there is a circular pond inside of a rectangular field and the cannon shoots cannonballs into the field.
we need to use functions, and i'm stuck on one that's supposed to have parameters: pond radius, x hit spot, and y hit spot. The function then plots the point x, y in one of two styles depending on whether it landed in the pond or not.
The plot function accepts a third argument that indicates the shape of the point to plot and the point's color. For instance this plots a blue asterisk: plot(x, y, 'b*') and this plots a green circle: plot(x, y, 'go') The statements in the function must do this: If the shot hit the pond, plot a blue star, otherwise plot a green circle. You will need to use an if/else statement, and you will need to call the hitPond function and the plot function. Also,this function mustreturn a result: • It returns true if the shot lands in the pond. • It returns false if the shot lands in the field. Be very careful here: The function should not display true or false, it should return true or false. Also note that the choice of using true and false as return values is completely arbitrary. I could have chosen −1 and 1, or 1 and 0, or 99 and 33, or even strings like 'splash' and 'thud'.
so far, what i have is:
.m function
function []=setupField(fieldSize)
title('Shots fired into a field with a perfectly round pond');
axis([-fieldSize/2, fieldSize/2, -fieldSize/2, fieldSize/2]);
axis equal;
hold on;
end
plotpond.m
function []=setupField(fieldSize)
title('Shots fired into a field with a perfectly round pond');
axis([-fieldSize/2, fieldSize/2, -fieldSize/2, fieldSize/2]);
axis equal;
hold on;
end
if true
% code
end
hitPond.m
function hitPond(pondRadius, xhit, yhit)
%use distance formula to find length between points.
x=0
y=0
%because of the axis^
%we are finding the distance between the axis and the point where it hit
step1=(xhit-x)^2;
step2=(yhit-y)^2;
step3=step1+step2;
distance=sqrt(step3);
if (distance<1);
disp('1');
elseif distance=1;
disp('1');
elseif distance>1;
disp('0');
end
end
driver script, monteCarlo.m
clc %clear commands
clear %clear all variables
clf % clear plot area
rng('shuffle') %shuffle random number generator
fieldSize = 4;
pondRadius= 1;
numShots = 100;
setupField(fieldSize);
x=0;
y=0; %axis should be 0,0
radius=1; %radius will be 1.
plotPond(x, y, radius)
hitPond(1, 1, 1)
So I guess I just need help on writing that function from earlier.
Thanks in advance for your help.
0 个评论
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!