计算使用蒙特卡洛方法PI给IM precise答案 [英] Calculating PI using Monte Carlo method gives imprecise answer

查看:205
本文介绍了计算使用蒙特卡洛方法PI给IM precise答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用蒙特卡洛方法计算PI。我的code给出结果3.000无论MAXLEN有多大。调试它很多次之后,我不能让我在做什么错。

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;#定义SQR2(X)((X)*(X))
FRAND的#define()((双)兰特()/(RAND_MAX))
#定义MAXLEN 1000
INT外切(INT半径){
    浮XCOORD = FRAND();
    浮YCOORD = FRAND();
    浮动坐标= SQR2(XCOORD)+ SQR2(YCOORD);    如果(坐标< =半径)
        返回1;
    返回-1;
}诠释的main()
{
    INT I;
    INT圈= 0,RECT = 0 ;;
    对于(i = 0; I< MAXLEN,我++)
    {
        如果(外切(1)大于0)//如果(外切(1))建议立即进行删除够,但它不工作。很奇怪在我看来。
            圈++;
        RECT ++; //这是等于MAXLEN,我只是把它用于调试
    }    浮PI = 4 *圈/ RECT;
    的printf(PI是%2.4f:\\ n,PI);
    返回0;
}


解决方案

由于圈子 RECT 都是 INT 4 *圆/矩形的结果将是 INT 。使用浮点数来代替。

 浮动PI = 4.0 *(浮点)圆/ RECT;

I am trying to calculate PI using Monte Carlo method. My code gives the result 3.000 no matter how big MAXLEN is. After debugging it many times, I couldn't get what I'm doing wrong.

#include <stdio.h>
#include <stdlib.h>

#define sqr2(x) ((x)*(x))
#define frand() ((double) rand() / (RAND_MAX))
#define MAXLEN 1000


int circumscribed(int radius){
    float xcoord = frand();
    float ycoord = frand(); 
    float coord = sqr2(xcoord) + sqr2(ycoord);

    if(coord <= radius)
        return 1;
    return -1;      
}

int main()
{
    int i;
    int circles = 0, rect = 0;;
    for(i = 0; i < MAXLEN; i++)
    {
        if(circumscribed(1) > 0)   // if(circumscribed(1)) shoul be enough but it doesn't work. Very odd in my opinion.
            circles++;
        rect++;  //this is equal to MAXLEN, I just used it for debugging
    }

    float PI = 4 * circles / rect;
    printf("PI is %2.4f: \n", PI);
    return 0;   
}

解决方案

Since circles and rect are both int, the result of 4 * circles / rect will be an int. Use floating point numbers instead.

float PI = 4.0 * (float)circles / rect;

这篇关于计算使用蒙特卡洛方法PI给IM precise答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆