I am trying to write a program that calculates the distance between two points of which x and y coordinates are entered by the user.
Coordinates are assigned to variables defined as double.
Program uses pythagorean theorem to calculate the distance and I can see that the sqrt function that I use by including <cmath> header file rounds up the result which I thing it should not.
Is there anything that I should to additional to increase the accuracy of the calculation executed by the sqrt function -or pow () function that I have already tried instead?-
I do run Visual Studio on an MBP running under Bootcamp and in fact getting the "Error 1 error C2666: 'pow' : 6 overloads have similar conversions" error message.
Code yields 8.76413 whereas the result must be as accurate as 8.764131445842194....
First off remember that float has LESS precision then double. Double gives you 16 significant figures while floats give 7 significant figures I believe. So when you are looking for high precision (Money calculations and other things) always use double. If you need even more precision then double can give use longdouble
If I am remembering right I believe doubles give 53 significant bits and floats always have 24 significant bits.
As for sqrt I can't really comment since I don't have much experience with it.
The most important thing is to use type double (or even longdouble) rather than float.
The other thing, if you want to actually display the full result, you will need to change the cout precision. Use something like cout.precision(15); or cout << setprecision(15); in order to show the output to 15 digits of precision for example.
You could try different methods of calculation, but in practice the results will be virtually identical in most cases: distance = pow(pow(x2 - x1, 2.) + pow(y2 - y1, 2.),.5);
Personally I'd prefer something like this, as it requires just a single function call, and it may be more accurate: distance = sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
I have re-written my code as follows and getting the same loss of precision.
I am starting to think that this has got to do something with my running Visual Studio on an MBP under bootcamp.
@ fcan1968 Are you sure there is any loss of precision? The code most recently posted uses the default settings of the output stream cout. That will usually show about 6 significant digits.
If you want the to display more digits, you need to do either
cout.precision(15);
or
cout << setprecision(15);
If you are using long double, you may try to display about 17 or 18 digits, usually. (you may be able to display more digits, but beyond that they may not be accurate).