1.通过蒙特卡洛模拟计算椭圆方程
的面积。
N = 1e6
a = 3
b = 2
f = 2*a * 2*b
x = 2*a * rand(N, 1) - a
y = 2*b * rand(N, 1) - b
c = (x.^2/a^2 + y.^2/b^2) <= 1
d = sum(c)
e = (d / N) * f
fprintf('通过蒙特卡洛模拟估算的椭圆面积为: %f', e)
2.通过蒙特卡洛模拟估算圆周率
的值。
N = 1e6
x = rand(N, 1)
y = rand(N, 1)
a = x.^2 + y.^2
b = sum(a <= 1)
pi = 4 * b / N
fprintf('通过蒙特卡洛模拟估算的圆周率pi的值为: %f', pi)
3. ![](https://i-blog.csdnimg.cn/direct/9ddcc21413254046bde472a4f3a38a4e.png)
years = [1790,1800,1810,1820,1830,1840,1850,1860,1870,1880,1890,1900,1910,1920,1930,1940,1950,1960,1970,1980,1990];
population = [3.9,5.3,7.2,9.6,12.9,17.1,23.2,31.4,38.6,50.2,62.9,76,92,106.5,123.2,131.7,150.7,179.3,204,226.5,251.4];
figure
plot(years,population)
title('某国人口数量')
xlabel('年份')
ylabel('人口(万)')
grid on;
a = 1790;
t = years - a;
b = log(population);
p = polyfit(t,b,1);
c = 2100-a;
d = polyval(p,c);
e = exp(d);
fprintf('预测2100年人口数为:%.2f万',e);
4.![](https://i-blog.csdnimg.cn/direct/427eb087171f463e80a9c1f5cb32ad67.png)
v = 1;
dt = 0.01;
t = 10;
A = [-2, 2; 2, 2; 2, -2; -2, -2];
N = round(t / dt);
B = zeros(4, N, 2);
B(:, 1, :) = A;
a = [2, 3, 4, 1];
for t = 2:N
for i = 1:4
b = A(i, :);
c = A(a(i), :);
d = (c - b) / norm(c - b);
f = b + v * dt * d;
B(i, t, :) = f;
A(i, :) = f;
end
end
figure;
hold on;
axis equal;
grid on;
plot([-2, 2, 2, -2, -2], [2, 2, -2, -2, 2]);
for i = 1:4
plot(B(i, :, 1), B(i, :, 2), '-');
end
title('四人的螺旋运动轨迹');
xlabel('X');
ylabel('Y');
hold off;
注:有的代码在每行结尾没加英文' ; ',但没影响运行就没管,应该有的。