和你前面问的题目一样的逻辑,随机投点
代码:- percent<-function(x0=10,y0=20,a=5,b=4,rectangle_num=30,MonteCarlo_point_num=1000){
- rectangle_center_x=runif(rectangle_num)*x0
- rectangle_center_y=runif(rectangle_num)*y0
- randpoint_x=runif(MonteCarlo_point_num)*x0
- randpoint_y=runif(MonteCarlo_point_num)*y0
- point_num_in_rectangle=0
- for (i in 1:MonteCarlo_point_num){
- mark=0
- for(j in 1:rectangle_num){
- if((randpoint_x[i]-rectangle_center_x[j])<(a/2) && (randpoint_y[i]-rectangle_center_y[j])<(b/2)){
- mark=mark+1
- }
- }
- if(mark>0){
- point_num_in_rectangle=point_num_in_rectangle+1
- }
- }
- percent=point_num_in_rectangle/MonteCarlo_point_num
- return(percent)
- }
- percent(10,20,5,4,30,1000)
复制代码 多运行点,画图:- result=0
- for(i in 1:100){result[i]<-percent(100,300,5,4,30,1000)}
- hist(result)
复制代码 请参考:
http://www.r-china.net/forum.php?mod=viewthread&tid=331
http://www.r-china.net/forum.php?mod=viewthread&tid=329
|