cfloating-point-precisiondouble-precision

Is float better than double sometimes?


I was solving this problem on spoj http://www.spoj.com/problems/ATOMS/. I had to give the integral part of log(m / n) / log(k) as output. I had taken m, n, k as long long. When I was calculating it using long doubles, I was getting a wrong answer, but when I used float, it got accepted.

printf("%lld\n", (long long)(log(m / (long double)n) / log(k)));

This was giving a wrong answer but this:

printf("%lld\n", (long long)((float)log(m / (float)n) / (float)log(k)));

got accepted. So are there situations when float is better than double with respect to precision?


Solution

  • A float is never more accurate than a double since the former must be a subset of the latter, by the C standard:

    6.2.5/6: "The set of values of the type float is a subset of the set of values of the type double; the set of values of the type double is a subset of the set of values of the type long double."

    Note that the standard does not insist on a particular floating point representation although IEEE754 is particularly common.