2013-07-16 149 views
0

我在while循環中有以下一段代碼,我用exp()函數計算了一些概率。無論在循環的第7次迭代中對程序 的輸入是什麼,exp都返回nan。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 

在這兩種情況下,使用的變量都具有完全相同的值。

+3

如果在GDB提示符下輸入'p((double(*)(double))exp)( - (new-old)/ temperature)',事情會改變嗎?如果是這樣,你是否#include '? (我聞到一個隱含的聲明。) – zwol

+0

哦,如果這不能解決問題,請嘗試'valgrind'。這不是顯而易見的內存損壞,但它可能是微妙的內存損壞。 – zwol

+0

沒有什麼改變,我包括數學庫 – rex123

回答

0

扎克的直覺是對的。我的random_percent函數如下所示,並且round()宏未聲明。

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

這就是爲什麼你應該禁用隱式聲明。 –