Double multiplication and precision

Hello everyone!

I find some strange behavior with a double in multiplication with a non rational number concerning its precision. The precision of stdout is enough as seen in type-1 result. If I multiply it with 1/8, everything is fine. But If I but this non rational number into brackets, it results in a 0-value!

Can someone explain me, why a bracket in this case ruins the calculation?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

void test() {

  double d1 = 0.00001;
  double d2 = 0.0000001;
  double d3 = 0.000000001;

  std::cout << "type-1 : " << d3 << std::endl;
  std::cout << "type-2 : " << d3*1/8 << std::endl;
  std::cout << "type-3 : " << d3*(1/8) << std::endl;

}


Output:
1
2
3
type-1 : 1e-09
type-2 : 1.25e-10
type-3 : 0
d3*(1/8)

When both sides of the / operator are integers, it is treated as integer division and the result will be an integer. Therefore 1/8 is zero, which means the above line of code is the same as d3*0


EDIT:

d3*1/8 works because the compiler first does d3*1, which results in a double (since d3 is a double). It then does the result of that /8... and since one side is a double, it does floating point division. So it works as expected.

The other way you can solve this is to force the compiler to do floating point division by making either (or both) sides of the / operator a floating point:

d3*(1.0/8.0), for example, would work fine.
Last edited on
Arf yes of course, how could I forget this =/

1/8 = 0

which seems nonsense, solved using the modular division %

1%8 = 7

Sometimes I really forget the basics. Thanks for showing me the tree in the woods ;-)
Topic archived. No new replies allowed.