我在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
在这两种情况下,使用的变量具有完全相同的值。
答案 0 :(得分:0)
int random_percent(double probability){
int edge=round(100*probability);
return ((rand () % 100) < edge) ? 1 : 0;
}