搜索
首页后端开发Python教程python实现蒙特卡罗方法(代码示例)

python实现蒙特卡罗方法(代码示例)

Jan 14, 2019 am 11:29 AM
python数据分析

本篇文章给大家带来的内容是关于python实现蒙特卡罗方法(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

蒙特卡罗方法是一种统计模拟方法,由冯·诺依曼和乌拉姆提出,在大量的随机数下,根据概率估计结果,随机数据越多,获得的结果越精确。下面我们将用python实现蒙特卡罗方法。

1.首先我们做一个简单的圆周率的近似计算,在这个过程中我们要用到随机数,因此需要先使用import numpy as np导入numpy库。

2.代码实现:

import numpy as np

total = 8000000
count = 0

for i in range(total):
    x = np.random.rand()
    y = np.random.rand()
    dis = (x**2+y**2)**0.5
    if dis <p>3.在上面的程序中我们用8000000个随机数进行投放,这样得到的结果会更精确一些,运行程序需要一定的时间,最终得到的结果如下</p><p><span class="img-wrap"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/549/675/172/1547436392667253.png?x-oss-process=image/resize,p_40" class="lazy" title="1547436392667253.png" alt="python实现蒙特卡罗方法(代码示例)"></span></p><p>4.下面我们进行一项简单的应用,下图为我在画图工具中随便画的一个图,我们可以用蒙特卡罗方法来估算图中黑色部分的面积。</p><p   style="max-width:90%"><span class="img-wrap"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/583/174/740/1547436406520588.png?x-oss-process=image/resize,p_40" class="lazy" title="1547436406520588.png" alt="python实现蒙特卡罗方法(代码示例)"></span></p><p>5.上面的图形是不规则的,我们只需知道在投放大量随机数的情况下,随机数在黑色部分出现的概率,再用总面积相乘即可估算黑色部分的面积。我们知道,黑色的rgb编码为(0,0,0),所以需要统计rgb编码为(0,0,0)时随机数的投放概率即可。</p><p>6.代码实现:</p><pre class="brush:php;toolbar:false">from PIL import Image
import numpy as np

im = Image.open("C:/Users/21974/Desktop/handwrite2.PNG")
total = 9000000
count = 0
defin = 0
width = im.size[0]
height = im.size[1]

for i in range(total):    #用蒙特卡罗方法获得估计值
    x = np.random.randint(0, width-1)
    y = np.random.randint(0, height-1)
    k = im.getpixel((x, y))
    if k[0]+k[1]+k[2] == 0:
        count += 1
print(int(width*height*count/total))

for i in range(width):    #用遍历获得准确值
    for j in range(height):
        k = im.getpixel((i, j))
        if k[0] + k[1] + k[2] == 0:
            defin += 1
print(defin)

上面的代码可分为两部分,第一个for后面是用蒙特卡罗方法获得的面积的估计值,第二个for后面是用遍历所有像素点的方法获得的面积的精确值,获得两个输出后进行对比。

python实现蒙特卡罗方法(代码示例)

我们在上面的程序中采用了9000000个随机数,可以看出两个输出结果相差并不大。

以上是python实现蒙特卡罗方法(代码示例)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:segmentfault。如有侵权,请联系admin@php.cn删除
列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

说明如何将内存分配给Python中的列表与数组。说明如何将内存分配给Python中的列表与数组。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python数组中指定元素的数据类型?您如何在Python数组中指定元素的数据类型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什么是Numpy,为什么对于Python中的数值计算很重要?什么是Numpy,为什么对于Python中的数值计算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

讨论'连续内存分配”的概念及其对数组的重要性。讨论'连续内存分配”的概念及其对数组的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy阵列上可以执行哪些常见操作?在Numpy阵列上可以执行哪些常见操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的数据分析中如何使用阵列?Python的数据分析中如何使用阵列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器