Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would printing a variable change its value?

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 value, 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?

like image 773
Max Avatar asked Oct 10 '22 22:10

Max


1 Answers

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 :-).

like image 140
thiton Avatar answered Oct 13 '22 10:10

thiton