原理不做赘述,参见【数值计算方法】数值积分&微分-python实现 - FE-有限元鹰 - 博客园,直接上代码,只实现1d,2d积分,N维积分的蒙特卡洛方法也类似.
| from typing import Callable,Union,List |
| def MonteCarloInt2d(f:Callable,x:Union[float,List[float]], |
| y:Union[float,List[float]],n:int=10000)->float: |
| """蒙特卡洛2d积分""" |
| |
| import random |
| rseed=random.randint(0,10000) |
| np.random.seed(rseed) |
| n=int(n) |
| low_x,high_x=x |
| low_y,high_y=y |
| |
| S=(high_x-low_x)*(high_y-low_y) |
| |
| xys=np.random.uniform(low=[low_x,low_y], high=[high_x,high_y], size=(n,2)) |
| return (S/n)*sum([f(xys[ind,0],xys[ind,1]) for ind in range(xys.shape[0])]) |
| |
| def MonteCarloInt2d(f:Callable,x:Union[float,List[float]], |
| y:Union[float,List[float]],n:int=10000)->float: |
| """蒙特卡洛2d积分""" |
| |
| import random |
| rseed=random.randint(0,10000) |
| np.random.seed(rseed) |
| n=int(n) |
| low_x,high_x=x |
| low_y,high_y=y |
| |
| S=(high_x-low_x)*(high_y-low_y) |
| |
| xys=np.random.uniform(low=[low_x,low_y], high=[high_x,high_y], size=(n,2)) |
| return (S/n)*sum([f(xys[ind,0],xys[ind,1]) for ind in range(xys.shape[0])]) |
| import scipy |
| def f(x): |
| return x**2 + 2*x + 1 |
| |
| a,b=-1,2 |
| v=MonteCarloInt1d(f,a,b,1e6) |
| print(f"integral of f(-1,2) is {v:.4f}") |
| |
| scipy_result,error = scipy.integrate.quad(f, a, b) |
| print(f"SciPy积分结果: {scipy_result},error: {error}") |
| |
| |
| |
| |
| from scipy.integrate import dblquad |
| def f(x, y): |
| return x**2 + y**2 |
| |
| |
| def scipy_integrate_2d(f, a, b, c, d): |
| result, error = dblquad(f, a, b, lambda x: c, lambda x: d) |
| return result |
| |
| a, b = 0, 1 |
| c, d = 0, 1 |
| |
| |
| monte_carlo_result = MonteCarloInt2d(f, [a,b],[ c, d]) |
| print(f"蒙特卡洛2d积分结果: {monte_carlo_result}") |
| |
| |
| scipy_result = scipy_integrate_2d(f, a, b, c, d) |
| print(f"SciPy 2d积分结果: {scipy_result}") |
| |
| |
| |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律