0

I know there is a lot of similar topics, but usually problem is different rounding, like 5 instead of 4, and the proper value is a double value because it have bigger precision. During making some stuff I met below problem. I wrote new, short program to present it. Why is this happening?

#include <iostream>

using namespace std;

int main()
{
    double lbs1 = 285.7;
    float lbs2 = 285.7f;

    double pds_left1 = lbs1 - int (lbs1);
    double pds_left2 = lbs2 - int (lbs2);

    cout << "1: " << pds_left1 << endl;
    cout << "2: " << pds_left2 << endl;

    return 0;
}

The result is:

1: 0.7

2: 0.700012

Community
  • 1
  • 1
RocketBall
  • 45
  • 6
  • 3
    @Borgleader I think this is a bit different, since OP is comparing `float` and `double` through truncation rather then summing floats. Probably https://stackoverflow.com/questions/2386772/difference-between-float-and-double is the duplicate. – kabanus Oct 19 '17 at 20:35
  • @kabanus afaik `lbs2 - int (lbs2)` is a subtraction of floats. It's the exact same thing. Yes there was a conversion to int right before to get the integral part but in the end that line subtracts 2 floats which makes the other link an adequate duplicate in my book. (side note: you could replace the conversion to int with std::floor and get [the same result](http://coliru.stacked-crooked.com/a/41c3ddf8d8b7a29a)) – Borgleader Oct 19 '17 at 20:40
  • Thank you for all links. Except this difference (I convert float to int, add float and int, convert to double) I have noticed one other: my error is in the 5th (!!!) decimal place, while other people get them mach further, like in 17th decimal place. – RocketBall Oct 19 '17 at 20:44
  • @Borgleader Thank you. I will leave my previous comment as it is. But still I don't know why my error is so big? – RocketBall Oct 19 '17 at 20:46
  • @RocketBall AFAIK most of the precision in floating point is concentrated near 0-1, the farther from that you are the bigger the jumps so you get bigger gaps with a number like 285 than you do with a smaller one. ([see here](http://coliru.stacked-crooked.com/a/46e92571ec11c3d7)) – Borgleader Oct 19 '17 at 21:00
  • @RocketBall: relative error is not big, it is the usual ~1e-8 for floats. – geza Oct 19 '17 at 21:02
  • 1
    Your error is big because you're using subtraction, which cancels out the high digits. If your `285.7` rounds to `285.700012` as a `float`, it is good to 7 digits just as one would expect. Do the subtraction and now it's only 4 good digits. That's math, not floating point. – Mark Ransom Oct 19 '17 at 21:25

0 Answers0