gpt4 book ai didi

c - exp() 函数不应该返回 nan

转载 作者:行者123 更新时间:2023-11-30 17:49:46 41 4
gpt4 key购买 nike

我在 while 循环中有以下代码段,其中我使用 exp() 函数计算一些概率。无论程序的输入是什么在循环的第 7 次迭代中,exp 返回 nan。

  if(new<=old){
coloring[random_node]=random_color;
}else{
proba=exp((-(new-old))/temperature);
/*assert(!isnan(proba));*/
printf("proba == %.50f\n",proba);
if(random_percent(proba)){
coloring[random_node]=random_color;
}
}

以下是循环内第6次和第7次迭代的调试信息。

Breakpoint 1, graph_coloring_local_search (objectiveValue=50, N=50, E=350, edge_list=0x804d170, node_list=0x804dc68, maxIterations=100, 
initial_temperature=7) at coloring.c:391
391 proba=exp((-(new-old))/temperature);
(gdb) p new
$21 = 1
(gdb) p old
$22 = 0
(gdb) p temperature
$23 = 6.9992999999999999
(gdb) p -(new-old)/temperature
$24 = -0.14287143000014288
(gdb) p ((double(*)())exp)(-(new-old)/temperature)
$25 = 0.8668655146301385
(gdb) c
Continuing.
proba == 0.86686551463013850060690401733154430985450744628906

Breakpoint 1, graph_coloring_local_search (objectiveValue=50, N=50, E=350, edge_list=0x804d170, node_list=0x804dc68, maxIterations=100,
initial_temperature=7) at coloring.c:391
391 proba=exp((-(new-old))/temperature);
(gdb) p new
$26 = 1
(gdb) p old
$27 = 0
(gdb) p temperature
$28 = 6.9992999999999999
(gdb) p -(new-old)/temperature
$29 = -0.14287143000014288
(gdb) p ((double(*)())exp)(-(new-old)/temperature)
$30 = -nan(0x8000000000000)
(gdb) c
Continuing.
proba == -nan

在这两种情况下,使用的变量具有完全相同的值。

最佳答案

扎克的直觉是对的。我的 random_percent 函数如下所示,并且未声明 round() 宏。

int random_percent(double probability){ 
int edge=round(100*probability);
return ((rand () % 100) < edge) ? 1 : 0;
}

关于c - exp() 函数不应该返回 nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17685422/

41 4 0