M. Smith
M. Smith

Reputation: 9

Function in a header file

I have a function defined in a C header file, where the array of m_parameters[] is defined elsewhere (just a list of numbers):

inline double Par3D::getValue(const double& x, const double& t ) const {
  double g1 = m_parameters[3] + m_parameters[4]*TMath::ATan(m_parameters[5]*(t-0.3)) ;
  double g0 = m_parameters[0] + m_parameters[1]*TMath::ATan(m_parameters[2]*(t-0.3)) ;
  return  g0  +  g1*TMath::ATan(m_parameters[6]*(x-0.3)) ;
}

This function is called repeatedly in a larger program. I get different results if I just put the expressions for g0 and g1 directly in the argument of the return. Is that to be expected?

Many thanks.

Upvotes: 0

Views: 104

Answers (1)

Tony Delroy
Tony Delroy

Reputation: 106096

It is to be expected. The C++ Standard gives the compiler the freedom to optimise in various ways, one of which is to use floating point registers in the CPU to store intermediate results, rather than using actual Random Access Memory to write back a double. On some hardware, the process of writing back to double requires rounding. For example, modern Intel CPUs have 80 bit floating point registers, but doubles are represented in 64 bits in memory. So - rounding earlier can lead to different results.

FWIW (not much) - if you enable optimisation you might find a register is used consistently, while without optimisation the compiler's likely to follow your code naively and round to a variable in memory as implied by the use of local variables.

Upvotes: 1

Related Questions