- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
注意,我是一个 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
正确设置种子) )。
至于你的循环问题 - 你永远不会改变那里的 x
或 y
的值。您应该在每次迭代时调用 throwDart
来获取 x
和 y
的新值:
for (int i = 0; i < N; i++)
{
throwDart(&x, &y);
if (y <= Fun(x))
c++;
}
关于C - 蒙特卡洛积分 - 随机不是随机且计数不计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28777088/
我应该在一些蒙特卡洛模拟中计算标准偏差函数。公式是这样的: 我认为我的结果与应有的结果相去甚远。我的函数使用来自 boost 库的元组,它看起来像这样: double add_square(doubl
我需要使用 R 代码执行股票价格模拟。问题是代码有点慢。基本上我需要模拟每个时间步长(每天)的股票价格并将其存储在矩阵中。 假设股票过程是几何布朗运动的例子 for(j in 1:100000){
如何在卷积神经网络中使用 Keras 实现 Monte Carlo dropout 以估计 YARIN GAL 建议的预测不确定性?我正在使用 R。R-Code is here 我正在小批量地拟合模型
我是一名优秀的程序员,十分优秀!