1

I have a simple number division. I have this two number:

  • 39.654
  • 8.381903173E-8

So, if I do the division on C:

// ...
float ii = 39.654;
double bb = 8.381903173E-8;
printf("\n%.20f\n", ii/bb);
// ... 

The output is: 473090639.56200009584426879883

But, if I work on Python3:

39.654/8.381903173E-8

The output is: 473090647.5719557

If I use a calculator, indeed, the true value is that of Python3

What is wrong with my C code?

Thanks! Regards!

DYZ
  • 55,249
  • 10
  • 64
  • 93
Emmanuel Arias
  • 484
  • 4
  • 11
  • 2
    Possibly related: https://stackoverflow.com/questions/13542944/how-many-significant-digits-have-floats-and-doubles-in-java – 0x5453 Aug 27 '18 at 18:16
  • 1
    [Single-precision values](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) can only represent so many places before they break down. You're at the limit here with values >1e9 where there will be a lot of approximation beyond ~8 places as there's only 23 bits to represent the actual numerical part. Only use `float` if you want to sacrifice accuracy in order to boost performance, something often imperative when doing real-time 3D math. – tadman Aug 27 '18 at 18:26

1 Answers1

9

You must compare apples to apples. In Python, all floating-point variables are of type double, so you should use the same data type in your C program:

double ii = 39.654;
double bb = 8.381903173E-8;
printf("\n%.20f\n", ii/bb);
DYZ
  • 55,249
  • 10
  • 64
  • 93
  • Consider `ii` as `float` and `bb` as `double`. When we do `ii/bb` shouldn't the `ii` be promoted to double for this operation? – dodobhoot Aug 27 '18 at 18:17
  • 4
    @dodobhoot It will be promoted. But its original accuracy (and value) will be that of a `float`. – DYZ Aug 27 '18 at 18:22
  • @EmmanuelArias after making that correction the program outputs `473090647.57195568084716796875` which agrees with Python. BTW didn't you get a compiler warning: *'initializing': truncation from 'double' to 'float'* ? – Weather Vane Aug 27 '18 at 18:49
  • holy... yeah! my problem was that! I tried to compare apples with cars. I think that this is the problem about use Python from some time ago. @WeatherVane I did not get any warning. – Emmanuel Arias Aug 27 '18 at 19:08