蒙特卡洛模拟稳定性的代码
时间: 2024-04-14 09:07:29 浏览: 25
蒙特卡洛模拟是一种基于概率统计的方法,可以用于评估复杂系统的稳定性。以下是一个简单的 Python 代码示例,演示如何使用蒙特卡洛模拟评估一个函数在给定参数范围内的稳定性:
```python
import random
def my_function(x, y):
# 假设这是我们要评估的函数
return x**2 + y**2
def monte_carlo_sim(iterations, x_range, y_range):
# iterations: 模拟迭代次数
# x_range: x的取值范围,格式为 (min, max)
# y_range: y的取值范围,格式为 (min, max)
results = []
for i in range(iterations):
x = random.uniform(x_range[0], x_range[1])
y = random.uniform(y_range[0], y_range[1])
result = my_function(x, y)
results.append(result)
return results
# 示例用法:
iterations = 10000
x_range = (-10, 10)
y_range = (-5, 5)
sim_results = monte_carlo_sim(iterations, x_range, y_range)
print("Mean value:", sum(sim_results) / len(sim_results))
print("Standard deviation:", (sum([(x - sum(sim_results)/len(sim_results))**2 for x in sim_results]) / len(sim_results))**0.5)
```
在这个例子中,我们定义了一个简单的函数 `my_function`,它接受两个参数 `x` 和 `y`,并返回它们的平方和。然后,我们编写了一个名为 `monte_carlo_sim` 的函数,该函数使用随机数生成器来模拟 `iterations` 次函数调用,并将结果存储在列表中。最后,我们计算模拟结果的平均值和标准差,以评估函数在给定参数范围内的稳定性。
请注意,这个示例代码仅是一个基本实现,可能需要根据具体情况进行修改和优化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)