Блог пользователя maniratnagupta

Автор maniratnagupta, история, 6 лет назад, По-английски

291B. Han Solo and Lazer Gunmysolution

I am using slopes concept in 2d geometry

  • Проголосовать: нравится
  • -18
  • Проголосовать: не нравится

»
6 лет назад, # |
  Проголосовать: нравится +8 Проголосовать: не нравится

Welcome to the wonderful world of floating-point numbers!

  • »
    »
    6 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Can you explain me more clearly

    • »
      »
      »
      6 лет назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      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.