0

我在 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

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

4

1 回答 1

0

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

int random_percent(double probability){ 
    int edge=round(100*probability); 
    return ((rand () % 100) < edge) ? 1 : 0;  
}
于 2013-07-16T20:19:43.703 回答