You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.4 KiB
62 lines
1.4 KiB
|
|
%27页例题
|
|
clc; clear; close all;
|
|
n = 10000; % 使用较小的 n 值以便更容易可视化
|
|
x = unifrnd(0, 12, [1, n]);
|
|
y = unifrnd(0, 9, [1, n]);
|
|
ans=sum(y < x.^2 & x <= 3)+sum(y < 12 - x & x >= 3);
|
|
ans=ans/n;
|
|
% 找出满足条件的点
|
|
condition1 = y < x.^2 & x <= 3;
|
|
condition2 = y < 12 - x & x >= 3;
|
|
condition_met = condition1 | condition2; % 满足任一条件的点
|
|
condition_not_met = ~condition_met; % 不满足任何条件的点
|
|
|
|
% 创建图形窗口
|
|
figure;
|
|
hold on;%在同一张图上绘图
|
|
|
|
% 绘制不满足任何条件的点
|
|
scatter(x(condition_not_met), y(condition_not_met), 'k.'); % k----黑色 .----绘制样式
|
|
%scatter绘制散点图
|
|
%x(condition_not_met) 会返回一个新的向量,其中只包含 x 中对应 condition_not_met 为 true 的元素。
|
|
|
|
% 绘制满足第一个条件的点
|
|
scatter(x(condition1), y(condition1), 'r.'); % 红色
|
|
|
|
% 绘制满足第二个条件的点
|
|
scatter(x(condition2), y(condition2), 'b.'); % 蓝色
|
|
|
|
% 添加图例和标签
|
|
legend('不满足任何条件的点', '满足 y < x^2 且 x <= 3 的点', '满足 y < 12 - x 且 x >= 3 的点');
|
|
xlabel('x');
|
|
ylabel('y');
|
|
title('随机生成的点和满足条件的点');
|
|
hold off;
|
|
|
|
|
|
%蒙特卡洛法求圆周率qw
|
|
clc;clear;close all;
|
|
|
|
n=10^5;
|
|
x=unifrnd(-1,1,[1,n]);
|
|
y=unifrnd(-1,1,[1,n]);
|
|
con1=x.^2+y.^2<=1;
|
|
con2=~con1;
|
|
ans=sum(x.^2+y.^2<=1);
|
|
ans=ans/n*4;
|
|
|
|
figure ;
|
|
hold on;
|
|
|
|
scatter(x(con1),y(con1),'r.');
|
|
scatter(x(con2),y(con2),'k.');
|
|
|
|
hold off;
|
|
|
|
|
|
|
|
|
|
|
|
|