floating point - C++ double division and return -


i understand doubles approximations. surprised

double f(int x, int y) {     return double(x)/y; } 

and

double f(int x, int y) {     double z = double(x)/y;     return z; } 

can return different values. know why?

the main reason "why" standard allows (except i'm not 100% sure does). pragmatic reason on processors (including intel 32 bit processors), floating point registers have more precision double. intermediate calculations done in registers, if fit (and standard allows intermediate results have more precision), results of given expression depend on how compiler manages registers, , when spills memory. , many (most?) compilers such processors return floating point values in register, keep precision. (i'm not sure legal. when assigning double, , think when copy constructing double, value must made fit. returning value copy construction, think should force double fit. regardless... compilers don't have deal it, regardless of standard might or might not have it.)

i think can prevent explicitly casting final results, i.e.:

return double( double(x)/y ); 

, i'm not sure (neither standard says it, nor compilers do).

note whether results different or not depends on them. if assign them double, or pass them function requires double, happens rounding occurs little later (but still on same value). if use value in expression, however, bets off. in case, 2.0 * f( a, b ) might result in different value depending on implementation of f, after rounding. , noticeably, f( a, b ) == f( a, b ) may return false. (i've seen case caused std::sort crash. comparison function used did along lines of return lhs.f() < rhs.f();, , returning true when lhs , rhs references same object; compiler spilled results of first function called memory, did comparison value in register second function returned.)


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -