数学趣题——求圆周率的近似值

应用数值概念算法求圆周率

数值概念算法(随机数方法):利用概率论解决问题,

在求圆周率时的核心思想是:

在一个边长为r的正方形中,以中心点为圆心,r为直径作圆,则圆的面积是1/4πr平方,而正方形面积是r平方。二者比值就是1/4π。

所以随机向该正方形投入点,其中落在圆内的概率的4倍就是圆周率。

源码:

   1: #include <string.h>
   2: #include <stdlib.h>
   3: #include <stdio.h>
   4: double GetPI(int n);
   5:  
   6: int main()
   7: {
   8:     double PI;
   9:     int n;
  10:     printf("input the number of random points for test\n");
  11:     scanf("%d", &n);
  12:     PI = GetPI(n);
  13:     printf("PI is %f\n", PI);
  14:     return 0;
  15: }
  16:  
  17: double GetPI(int n)
  18: {
  19:     int nInCircle = 0;
  20:     float x, y;
  21:     int nCount = n;
  22:     while (nCount)
  23:     {
  24:         x = random(101);
  25:         y = random(101);
  26:         if (x*x + y*y <= 10000)
  27:         {
  28:             nInCircle++;
  29:         }
  30:         nCount--;
  31:     }
  32:     return 4.0*nInCircle/n;
  33: }
原文地址:https://www.cnblogs.com/steven_oyj/p/1744122.html