maniratnagupta's blog

By maniratnagupta, history, 6 years ago, In English

291B. Han Solo and Lazer Gunmysolution

I am using slopes concept in 2d geometry

  • Vote: I like it
  • -18
  • Vote: I do not like it

| Write comment?
»
6 years ago, # |
  Vote: I like it +8 Vote: I do not like it

Welcome to the wonderful world of floating-point numbers!

  • »
    »
    6 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Can you explain me more clearly

    • »
      »
      »
      6 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Sorry, I wanted to write a little more, but then got distracted.

      Basically floating point numbers are not precise. A computer can only hold a limited number of digits (here binary digits). E.g. executing the following C++ code gives 0.6666666865.

      cout << fixed << setprecision(10);
      cout << (float)2 / 3 << '\n';
      

      Therefore normally if you do some floating point arithmetik, then all your intermediate results will be slightly wrong, and you cannot compare values with == any more. E.g. the following code will assign b with false, since for the computer 0.3 * 3 + 0.1 will actually be slightly less than 1.

      bool b = (0.3 * 3 + 0.1) == 1
      

      If you want to compare two floating point values, you have to do it using a small epsilon.

      if (abs(x - y) < 1e-8)
      // instead of 
      if (x == y)
      

      Another thing. Always use double instead of float!

      Now to your code. I did some little testing, and actually this floating point problem might not actually be the case why your code doesn't work. Sorry. I guess I was a little bit to quick by judging your code.

      Here's some small test case for you:

      2 0 0
      0 1
      0 -1
      

      Your code returns 2, although clearly all three points are on 1 line. The reason is, that 1/0 will give +infinity, and -1/0 will give -infinity. So you have to handle that case separately.