0

I am writing a program for class that simply calculates distance between two coordinate points (x,y).

differenceofx1 = x1 - x2;
differenceofy1 = y1 - y2;
squareofx1 = differenceofx1 * differenceofx1;
squareofy1 = differenceofy1 * differenceofy1;
distance1 = sqrt(squareofx1 - squareofy1);

When I calculate the distance, it works. However there are some situations such as the result being a square root of a non-square number, or the difference of x1 and x2 / y1 and y2 being negative due to the input order, that it just gives a distance of 0.00000 when the distance is clearly more than 0. I am using double for all the variables, should I use float instead for the negative possibility or does double do the same job? I set the precision to 8 as well but I don't understand why it wouldn't calculate properly?

I am sorry for the simplicity of the question, I am a bit more than a beginner.

Shabaz Terran
  • 23
  • 1
  • 4
  • 4
    Usually, for distance, it's `distance1 = sqrt(squareofx1 + squareofy1);` – fefe Sep 08 '17 at 05:09
  • 1
    "or the difference of x1 and x2 / y1 and y2 being negative due to the input order" Doesn't matter, the square will be positive. – tkausl Sep 08 '17 at 05:10
  • `float` is for single precision floating point values. `double` is for double precision floating point values. Both types are used for floating point values, but `double` have higher precision and can represent larger or smaller numbers. – Some programmer dude Sep 08 '17 at 05:10
  • why would it give distance as 0 for some situations tho even tho the difference isn't 0? – Shabaz Terran Sep 08 '17 at 05:12
  • 2
    Because its `a² + b² = c²`, not `a² - b² = c²`, as @fefe already pointed out. – tkausl Sep 08 '17 at 05:13
  • And we normally use the `std::hypot()` library function defined in ``, which helps avoid overflow and precision problems, rather than reimplementing it with basic arithmetic like this. – Toby Speight Sep 08 '17 at 15:08

2 Answers2

0

You are using the distance formula wrong it should be distance1 = sqrt(squareofx1 + squareofy1); instead of distance1 = sqrt(squareofx1 - squareofy1); due to the wrong formula if squareofx1 is less than squareofy1 you get an error as sqrt of a negative number is not possible in case of real coordinates.

0

Firstly, your formula is incorrect change it to distance1 = sqrt(squareofx1 + squareofy1) as @fefe mentioned. Btw All your calculation can be represented in one line of code:

distance1 = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

No need for variables like differenceofx1, differenceofy1, squareofx1, squareofy1 unless you are using the results stored in these variables again in your program.

Secondly, Double give you more precision than float. If you need precision more than 6-7 places after decimal use Double else float works too. Read more about Float vs Double

Quentin
  • 62,093
  • 7
  • 131
  • 191
Ishpreet
  • 5,230
  • 2
  • 19
  • 35