Is float better than double sometimes?

179 Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

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.

2
On

double will always give you more precision than a float. With double, you encode the number using 64 bits, while your using only 32 bits with float.

Edit: As Jens mentioned it may not be the case. double will give more precision only if the compiler is using IEEE-754. That's the case of GCC, Clang and MSVC. I haven't yet encountered a compiler which didn't use 32 bits for floats and 64 bits for doubles though...

0
On

It might be better in some cases in terms of calculation time/space performance. One example that is just on the table in front of me - an ARM Cortex-M4F based microcontroller, having a hardware Floating Point Unit (FPU), capable of working with single-precision arithmetic, but not with double precision, which is giving an incredible boost to floating point calculations.

7
On

Try this simple code :

#include<stdio.h>
int main(void)
{
    float i=3.3;
    if(i==3.3)
      printf("Equal\n");
    else
      printf("Not Equal\n");
    return 0;
}

Now try the same with double as a datatype of i.