-4

I have the following program:

float x = 3.e17;
printf("x = %f", x);

which gives the result:

x = 299999995292024832.000000

why is the result not 300000000000000000.000000?

Dovahkiin
  • 1,239
  • 11
  • 23
  • 2
    This is probably due to floating-point inaccuracy issues. Values of type `float` cannot represent all real numbers exactly and have a degree of rounding error for most values, which is likely what you're seeing here. – templatetypedef Jan 26 '16 at 19:58
  • 1
    @templatetypedef Not probably but definetely. – Oleg Andriyanov Jan 26 '16 at 19:58
  • @maxhb This is not a duplicate of that because the OP is comparing the `float` to the real value, not to a float literal. The OP would still have the same question with `double x = 3.e57;`, whereas the question you selected only exists with `float`. – Pascal Cuoq Jan 26 '16 at 23:10

2 Answers2

1

Because of limited float precision. Use double for more precision, but floating point is not always exact

Vasfed
  • 18,013
  • 10
  • 47
  • 53
1
#include <stdio.h>
#include <stdlib.h>

union
{
    double d;
    float f;
    unsigned int ui[2];
} myun;

int main ( void )
{
    float  fx = 3.e17;
    double dx = 3.e17;
    printf("fx %f\n",fx);
    printf("dx %lf\n",dx);
    myun.f=fx;
    printf("fx 0x%08X\n",myun.ui[0]);
    myun.ui[0]++;
    printf("fx %lf\n",myun.f);
    myun.d=dx;
    printf("dx 0x%08X 0x%08X\n",myun.ui[1],myun.ui[0]);
    return(0);
}

(yes this is an incorrect/invalid way to use a union but it just happened to work)

fx 299999995292024832.000000
dx 300000000000000000.000000
fx 0x5C853A0D
fx 300000029651763200.000000
dx 0x4390A741 0xA4627800

wikipedia points out that single can handle up to 9 digits without a loss of precision and double 15-17. So right there is your answer, didnt necessarily need to do an experiment.

old_timer
  • 69,149
  • 8
  • 89
  • 168
  • 1
    Noting that float and double can hold integers of more than respectively 9 and 17 digits depending on the number of 2s in these integer's decompositions into primes. 3*10^17 has 2^17 as a factor, so it more than easily fits in a double. – Pascal Cuoq Jan 26 '16 at 21:38