程序如下:
clear;clc
a=5;b=20;
t=-2*pi:0.001:2*pi;
x=a*sin(t);
y=b*cos(t);
plot(x,y)
xlist = []; % 存放结果的数组
ylist = [];
cnt = 0;
while cnt < 100%产生椭圆内点
x1 = randi(100,1,1)/10;%产生随机数
y1 =randi(100,1,1)/10;
if (x1/a)^2 + (y1/b)^2 < 1 % 判断是否在椭球内部
cnt = cnt + 1;
xlist(cnt) = x1;
ylist(cnt) = y1;
disp(['输出随即数 (' num2str(xlist(cnt)) ',' num2str(ylist(cnt)) ')'])
end
end
hold on
plot(xlist, ylist, '.r'); % 绘制点的分布的点
legend('椭圆' ,'随机点')
grid on
给你一个代码
clear;
clc;
close all;
N=1500;
a=20;
b=5;
num=0;
X=[];
Y=[];
while( num
yi=rand()*2-1;
if( xi^2 + yi^2 <= 1 )
X=[X; xi*a];
Y=[Y; yi*b];
num = num + 1 ;
end
end
t=[-pi:0.1:pi pi];
x=a*cos(t);
y=b*sin(t);
figure;
hold on;
grid on;
axis equal;
plot(X,Y,'b.')
plot(x,y,'color','r','LineWidth',1.5)
xlim([-20 20]);
ylim([-10 10]);
legend('随机点','椭圆')
效果图如下: