开发者

Why would printing a variable change its value?

开发者 https://www.devze.com 2023-04-08 15:02 出处:网络
I have a small function, which is supposed to make a prediction based on a machine learning algorithm. The function wasn\'t working, so I put a print statement in to check on the val开发者_JAVA百科ue,

I have a small function, which is supposed to make a prediction based on a machine learning algorithm. The function wasn't working, so I put a print statement in to check on the val开发者_JAVA百科ue, and all of a sudden it started working. When I comment out the print line, it stops working again. Is there something I'm missing about why this would happen?

int makePrediction( const InstanceT & instance, bool biased ){
  double dotProduct = ( biased ? instance * _weights + _bias : instance * _weights ); 
  std::cout << "dotProduct = " << dotProduct << std::endl;
  return ( dotProduct > 0 ? 1 : -1 );
}

for some reason produces a different result then

int makePrediction( const InstanceT & instance, bool biased ){
  double dotProduct = ( biased ? instance * _weights + _bias : instance * _weights ); 
  return ( dotProduct > 0 ? 1 : -1 );
}

and to show that the results are different given the same inputs, I call this function with:

std::vector<InstanceT> _instances = populate_data() //this works for both versions
for ( int i = 0; i < _instances.size(); i++ ){
  std::cout << "prediction: " << makePrediction( _instances[i], true ) << std::endl;
}

Any thoughts?


This often happens due to two reasons:

  1. Concurrency issues. If your program is multithreaded, you mask race conditions with debug output. Try a MT debugger like helgrind.
  2. Broken stacks. Try running valgrind on your program and see if it comes out clean.

These are, of course, pretty generic advices, but you'll have to specify your question better to get better advice :-).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号