0

I am wondering about the following: I have a method that takes a float as input and returns a float after some calculation. The calculations may involve anything like addition, division, logarithms, powers etcetera. While doing so, the intermediate result needs to be stored several times. Something crazy like this:

float performSomeComputations(float value)
{
    // addition, substraction, logarithms, multiplication, etcetera
    float a = value * 12.0;
    float b = math.pow(a, 34.0);
    float c = math.log10(b +  value - 567);
    return a + b + c;
}

My question is: does it matter how you store the intermediate results? I.e. as float or as double? Let us assume that the intermediate values don't exceed the minimum and/or maximum value, obviously there will be a difference then. But would the return value be more accurate if double types are used, or would you get always exactly the same answer, after it's finally cast back to float? And is it possible that the answer could vary per programming language?

Yellow
  • 3,955
  • 6
  • 45
  • 74

1 Answers1

0

It depends on the inputs of course. But having intermediate results in a higher precision than the final results is in my opinion a good idea because your result will be at least as accurate as if you had used the same precision.

If the calculations and numbers are such that the intermediate results' precision is somewhat higher, it may be that the final result is the same anyway. But this will not always be the case; in some cases, especially if there are complicated calculations that take many steps, the final result will be more precise because there is less loss of precision at every step.

Whether it depends on programming languages: it should not, but I would not rule it out entirely. Testing would be necessary to determine I suppose (or reading the language's or the compiler's documentation). Generally speaking I'd think that, since we're talking precision, the rule would apply always: your result will be at least as precise as in the case when you had not used more precise intermediates.

Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
  • Clearly the result will be "at least as accurate" with `double`s, but if it doesn't make a difference, why bother with all the casting? Could you give an example of a case where it does make a difference? – Yellow Oct 08 '13 at 10:40
  • *if there are complicated calculations that take many steps*... That would be an "opportunity" for precision loss at every step, but less so when the intermediate results are more precise. – Roy Dictus Oct 08 '13 at 10:42
  • Fair enough, but in the end, the `double` intermediate will be cast to a `float`, such that the extra precision is lost again. So how can you be sure that not **all** the extra precision will **always** be lost during that stage? In other words, how can you be sure that `double` intermediates are worthwhile? – Yellow Oct 08 '13 at 10:48