gpt4 book ai didi

C - 蒙特卡洛积分 - 随机不是随机且计数不计数?

转载 作者:行者123 更新时间:2023-11-30 15:23:30 24 4
gpt4 key购买 nike

注意,我是一个 C 新手:P

我试图找出为什么我的程序没有按预期运行。

首先,它应该返回 0.0 到 10.0 范围内的 x 和 y 值,确实如此,但每次运行后随机数不应该重置吗?每次运行程序时我都会得到相同的 X 和 Y 值。

其次,我的循环似乎没有做任何事情。计数根本没有增加,我不知道为什么 - 我假设这是固定的,我应该开始看到一些正确的结果。

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

void throwDart(double *x, double *y)
{
double min = 0.0, max = 10.0;

*x = (max - min) * ((double)rand() / (RAND_MAX)) + min; //don't nec. need min - example format
*y = (max - min) * ((double)rand() / (RAND_MAX)) + min; //^same
}

double Fun(double x)
{
return ((0.3*x*x) - (0.2*x) - 5); //estimate value of definite integral using this function
}

int main()
{
double x, y, P; //(x,y) is location, P is number of darts that hit below the curve/total thrown
int N, e; //N is number of darts, e is area under curve
int c = 0; //initialize count of darts that hit below the curve

throwDart(&x, &y);

printf("How many darts would you like to throw?\n");
scanf("%d", &N);

for (int i = 0; i < N; i++)
{
if (y <= Fun(x))
c++;
}

P = c/N;
e = 100.00 * P;

//most of the following prints just to see what is and isn't working
printf("X is %lf\n", x);
printf("Y is %lf\n", y);
printf("N is %d\n", N);
printf("c is %d\n", c);
printf("P is %d\n", P);
printf("Area under the curve is %d\n", e);

system("Pause");

}

最佳答案

random 使用的算法是伪随机。它取决于一个名为 seed 的值 - 如果您可以在每次启动程序时将其设置为不同的值,您将获得其他系列的随机数。默认情况下,seed 设置为 1,因此该系列不会更改。比较流行的方法是使用自纪元以来的秒数作为种子:

srand(时间(NULL));

srand 将伪随机生成器的种子更改为给定值,time 返回自纪元以来的秒数时间,因此每次调用时它都会使用不同的序列该程序。 srand 只能调用一次,最好是在 main 开头的某个位置(以确保为第一次调用 rand 正确设置种子) )。

至于你的循环问题 - 你永远不会改变那里的 xy 的值。您应该在每次迭代时调用 throwDart 来获取 xy 的新值:

for (int i = 0; i < N; i++)
{
throwDart(&x, &y);
if (y <= Fun(x))
c++;
}

关于C - 蒙特卡洛积分 - 随机不是随机且计数不计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28777088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com