0

This is a code for pythagorean triplet. Can somebodby explain the working of if statement below.

int main()
{
    int a, b;
    float c;

    //calculate the another side using Pythagoras Theorem
    //a*a + b*b = c*c
    //c = sqrt(a*a+b*b)
    //maximum length should be equal to 30
    for(a=1;a<=30;a++)
    {
        for(b=1;b<=30;b++)
        {
            c = sqrt(a*a+b*b);
            if(c == (int)c)
            {
                printf("(%d, %d, %d)\n",a,b,(int)c);
            }
        }
    }
}
user438383
  • 5,716
  • 8
  • 28
  • 43
bitcoder
  • 1
  • 1
  • The if statement is just checking whether the floating point variable `c` is same as its integer equivalent (by type casting `c` to `int`). – kiner_shah Sep 12 '21 at 07:28
  • 1
    This is an attempt to check if the result of `sqrt` is integer, however, it will fail if the result is outside of the `int` type range. – bereal Sep 12 '21 at 07:30
  • 1
    Generally speaking, whenever someone feels the need to do a C-style cast (like `(int) c`) then it should be taken as a red flag that there's something wrong going on. – Some programmer dude Sep 12 '21 at 07:32
  • So we are to check if calculated `c` is an int/whole number ? if it is, then we take it as a side of the triangle. – bitcoder Sep 12 '21 at 07:37
  • @Someprogrammerdude can u explain? – bitcoder Sep 12 '21 at 07:43

2 Answers2

0

It is checking whether the value is integral. 'c' is a float, the cast drops any fractional part. The original value of 'c' is then checked against the result of that cast. If they match then the original c was an integral value (note that even with this cast there are plenty of integral values that will fail this test, any value of 'c' larger than std::numeric_limits::max())

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23
  • It's worse than that. The integer 16,777,217 can't be accurately represented as a float according to https://stackoverflow.com/questions/3793838/which-is-the-first-integer-that-an-ieee-754-float-is-incapable-of-representing-e – Jerry Jeremiah Sep 12 '21 at 08:25
0

This if statement does not have to work because floating point (float, double, etc) representations in the processor are different from integers (int, char, etc). Therefore, in the general case, this kind of operator is erroneous.

Floating-point numbers are sometimes impossible to represent exactly as an integer (especially as a result of some kind of calculation) (see wiki and this question), and integers are always represented exactly.

In your case, one way to make the if statement correct is to write it like this:

if (fabs(c - roundf(c)) < eps) {
    ...
}

where eps is required accuracy. For example,

float eps = 1e-12;  // 10^(-12)
V. Fedulov
  • 41
  • 3