ipyparallel 中的 pi的求法
1.PI的求法的数学依据

如图,可以看见在边长为1的正方形里面,有一个1/4圆,我们随机在正方形中取点,点在圆内的概率和点在正方形内的概率之比正好为两者的面积之比.这样就有在圆内的点的数目比所有点的数目值应该为0.25*π*1/1=0.25π.只要我们随机取点的数目足够多,根据上述关系求得的π的精确率就越高.我们最终可以得到π=4*在圆内的点的数目/所有点的数目,据此,可以写出如下程序:
from numpy.random import rand
def sample(n):
return (rand(n)**2+rand(n)**2<=1).sum()
n=1000000
pi=4*sample(n)*1.0/n
print pi
输出:3.140556(此值可能会变化)
根据上述程序,可以将求π的程序改写成并行版本:
from ipyparallel import *
rc=Client()
dview=rc[:]
with dview.sync_imports():
from numpy.random import rand
def sample(n):
return (rand(n)**2+rand(n)**2<=1).sum()
n=1000000
list=[n]*len(dview)
#list 由 len(dview)个n构成,正好每一个engine一个
pi=4*sum(dview.map_sync(sample,list))*1.0/(n*len(dview))
print pi
输出:3.141763(每次输出都不一样)
ipyparallel 中的 pi的求法的更多相关文章
- 隱藏在素數規律中的Pi -- BZOJ1041解題報告
退役狗在刷程書的過程中看到了一個有趣的視頻, 講解了一個有趣的問題. 在網上隨便搜索了一下居然還真的找到了一道以它爲背景的OI題目, BZOJ1041. 下面的內容會首先回顧一下視頻所討論的知識, 有 ...
- OI中组合数的若干求法与CRT
OI中组合数的若干求法与CRT 只是下决心整理一下子呢~ 说明:本篇文章采用\(\binom{a}{b}\)而不是\(C_{a}^b\),以\(p\)指代模数,\(fac_i\)指代\(i!\),\( ...
- c++中sin,cos,arcsin等和在C/C++中使用pi (π) 值
先 #include<math.h> 反3角函数有 acos(double),asin(double),atan(double),atan(double,double),返回值 doubl ...
- 在PhpStorm9中与Pi的xdebug进行调试
PI的配置参考 http://www.cnblogs.com/yondy/archive/2013/05/01/3052687.html 在PhpStorm 9.0中参考下面的截图进行配置 配置完成以 ...
- pi的求法 acos(-1.0)
pi=acos(-1.0) https://www.luogu.org/problemnew/show/T4529 #include <cstdio> #include <cstdl ...
- # C++中对PI的引用
#include <iostream> #include <cmath> using namespace std; int main(){ printf("%.10l ...
- js jquery中 的数据类型
任何一门语言, buguan 是动态的, 还是像C语言的, 都有严格的 类型 "概念的", 这个是由于 编译器和解释器要求的, 需要的. 所以在是使用像 js, jquey ,ph ...
- [转]Raspberry Pi做成路由器
http://raspjason.blog.51cto.com/8565009/1426561/ 曾经看到很多文章把Raspberry Pi制作成无线AP,但是我今天要做的是把Raspberry Pi ...
- define宏定义中的#,##,@#及\符号
define宏定义中的#,##,@#及\符号 在#define中,标准只定义了#和##两种操作.#用来把参数转换成字符串,##则用来连接两个前后两个参数,把它们变成一个字符串. 1.# (string ...
随机推荐
- javascript中的正则匹配函数exec(),test(),match()
test() var str = "cat";var reStr = /cat/;alert(reStr.test(str)); 输出为:true 它的返回值为true or fa ...
- The Wall (medium)
The Wall (medium) Heidi the Cow is aghast: cracks in the northern Wall? Zombies gathering outside, f ...
- android 手势识别学习
引自http://www.cnblogs.com/android100/p/android-hand.html http://blog.csdn.net/jiangshide/article/d ...
- UIApplication,UIWindow,UIViewController,UIView(layer)
转载自:http://www.cnblogs.com/iCocos/p/4684749.html UIApplication,UIWindow,UIViewController,UIView(laye ...
- PAT (Advanced Level) 1078. Hashing (25)
二次探测法.表示第一次听说这东西... #include<cstdio> #include<cstring> #include<cmath> #include< ...
- 如何使用GOOLE
如何使用google http://www.kancloud.cn/yunzhiclub/google
- 前端UI
一个非常好的前端UI,值得研究下 http://semantic-ui.com/
- 对STM32的NVIC_PriorityGroupConfig使用及优先级分组方式理解(转)
源:http://blog.chinaunix.net/uid-22670933-id-3443085.html STM32有43个channel的settable的中断源:AIRC(Applicat ...
- CSS3 线型渐变
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Cantor表 1083
题目描述 Description 现代数学的著名证明之一是Georg Cantor证明了有理数是可枚举的.他是用下面这一张表来证明这一命题的: 1/1 1/2 1/3 1/4 1/5 - 2/1 2/ ...