0

How to enure the function return consistent floating point values in C/C++?

I mean: if a and b are of floating point type, if I wrote a polynomial function (which takes floating point argument and returns floating point results), lets call it polyfun(), do the compiler can ensure that:

if a==b, then polyfun(a)==polyfun(b), which means the order of maths ops/rounding up are consistent at runtime?

talonmies
  • 70,661
  • 34
  • 192
  • 269
user2188453
  • 1,105
  • 1
  • 12
  • 26

2 Answers2

3

Reproducible results are not guaranteed by the language standards. Generally, a C implementation is permitted to evaluate a floating-point expression with greater precision than the nominal type. It may do so in unpredictable ways, such as inlining a function call in one place and not another or inlining a function call in two places but, in one place, narrowing the result to the nominal type to save it on the stack before later retrieving it to compare it to another value.

Some additional information is in this question, and there are likely other duplicates as well.

Methods of dealing with this vary by language and by implementation (particularly the compiler), so you might get additional information if you specify what C or C++ implementation you are using, including the details of the target system, and if you search for related questions.

Community
  • 1
  • 1
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • +1. Note that the standard does not specify because different machines are different, and specifying a particular behavior would unfairly penalize some architectures. – Billy ONeal Aug 11 '13 at 00:07
  • It seems to me that this question is about obtaining reproducible results for one particular architecture and one particular compilation, that is, literally, inside the same program having been compiled and running on a given platform, does `a == b` imply `polyfun(a) == polyfun(b)`. Your answer are about portability across compilers and architectures. In other words, this question is only about the “solar flares” part of the other question you link to, and the answer is “no, I don't know any platform where floating-point is influenced by solar flares”. – Pascal Cuoq Aug 11 '13 at 05:45
  • That is how Jacob Pollack understood the question too according to his now deleted answer. – Pascal Cuoq Aug 11 '13 at 05:56
  • 1
    @PascalCuoq: This answer is about reproducibility in one program on one machine. As stated, `polyfun(x)` might be compiled to different code in different places in the same programm, due to inlining. Or to evaluation at compile-time in one place and not another. (E.g., suppose one call uses a constant argument and another a variable.) – Eric Postpischil Aug 11 '13 at 10:01
-1

Instead of polyfun(a)==polyfun(b) try ABS(polyfun(a) - polyfun(b)) < 1e-6, or 1e-12 or whatever you find suitably appropriate for "nearness"... (Yeah, cumulative float point errors will still kill you.)

guest
  • 1
  • 1