一種計算π的方法


假設點可以均勻的扔到正方形中。如果一共扔N次,其中M次扔進內切圓內,則可以推導出計算π的公式:

隨機計算π

大體思路:獲得隨機數(x,y),判斷x*x + y*y是否在單位圓內,可以得到M的個數。

程序

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 1000
int main()
{
    int i, M=0;
    double x, y, pi;
    srand((int)time(NULL));
    for (i=0; i<N; i++)
    {
        x = rand() / (double)RAND_MAX;
        y = rand() / (double)RAND_MAX;
        if (x*x + y*y < 1)
            M++;
    }
    pi = (4.0 * M) / N;
    printf("pi:%f\n", pi);
    return 0;
}

注意:有關隨機數的獲取可以參考:http://www.cnblogs.com/kaituorensheng/archive/2013/03/05/2944008.html

一組結果

畫出網格計算π

大體思路:

程序:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define n 10000000
int main()
{
    int i;
    double sum = 0;
    for (i=0; i<n; i++)
        sum += sqrt((double)n*n - (double)i*i);
    printf("%f\n", 4.0*sum /n/n);
}

一組結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM