zoukankan      html  css  js  c++  java
  • 蒙特卡洛算法

    简介

    随机取样法(别名),基于大量事件的统计结果来实现一些确定性问题的计算。
    其实很简单哦

    QU

    (y=x^2) (y=12-x) (y = 0) 围成的区域面积
    面积如下图所示

    感觉matlab对于这种程序真的很方面,如果用C++看来没有50+行是写不完了

    code

    clc,clear
    x = unifrnd(0,12,[1,10000000]); % doc unifrnd
    y = unifrnd(0,9,[1,10000000]);
    pinshu = sum(y < x.^2 & x <=3 ) + sum (y<12-x & x>=3);
    area_appr = 12 * 9 * pinshu / 10^7
    
    hold on;
    lx = [0:0.01:12];
    ly1 = lx.^2; %注意这里必须使用点乘。
    plot(lx, ly1);
    ly2 = 12 - lx;
    ly3 = 0;
    plot(lx,ly2);
    plot(lx,ly3);
    

    TIPS

    unifrnd 函数是什么意思呢?
    returns an array R of random numbers generated from the continuous uniform distributions with lower and upper endpoints specified by A and B, respectively. If A and B are arrays, R(i,j) is generated from the distribution specified by the corresponding elements of A and B. If either A or B is a scalar, it is expanded to the size of the other input.
    生成一个数组R连续均匀分布于最低值和最高值。
    R = unifrnd(A,B,m,n,...) or R = unifrnd(A,B,[m,n,...]) returns an m-by-n-by-... array. If A and B are scalars, all elements of R are generated from the same distribution. If either A or B is an array, they must be m-by-n-by-... .
    总而言之 生成了 (10^7) 个数据点,x和y
    sum 统计这些数据点 的分布个数。
    感觉这个算法简单又实在。过于优秀。
    美的总是简单又好用的。

    Result

    area_appr =

    49.5029

    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    解决UITableView中Cell重用机制导致内容出错的方法总结
    Hdu 1052 Tian Ji -- The Horse Racing
    Hdu 1009 FatMouse' Trade
    hdu 2037 今年暑假不AC
    hdu 1559 最大子矩阵
    hdu 1004 Let the Balloon Rise
    Hdu 1214 圆桌会议
    Hdu 1081 To The Max
    Hdu 2845 Beans
    Hdu 2955 Robberies 0/1背包
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/13440276.html
Copyright © 2011-2022 走看看