【问题标题】:exp() function returns nan when it should notexp() 函数在不应该返回 nan 时返回
【发布时间】:2013-07-15 03:47:40
【问题描述】:

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

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

【问题讨论】:

  • 如果您在 GDB 提示符下键入 p ((double(*)(double))exp)(-(new-old)/temperature),情况会发生变化吗?如果是这样,你是#include &lt;math.h&gt; 吗? (我闻到了隐含的声明。)
  • 哦,如果这不能揭示问题,请尝试valgrind。这不是明显内存损坏,但可能是微妙内存损坏。
  • 没有任何变化,我包含了数学库
  • @Zack 感谢您提供隐式声明的建议。在random_percent 函数中,我使用了一个未声明的圆形宏。
  • @Zack 我应该如何解决这个问题?

标签: c nan


【解决方案1】:

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

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

【讨论】:

  • 这就是为什么你应该禁用隐式声明。
猜你喜欢
  • 2018-10-11
  • 2012-05-20
  • 2019-04-24
  • 2021-12-20
  • 2022-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多