How to achieve higher precision?

Hello everyone.
I am writing a program to calculate the Speed of an object according to Einstein's Special Relativity.
The formula is really easy to implement into C++ and I'll share my approach here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <math.h>
#include <iostream>
#include <cstdio>

using namespace std;
int main()
{
	int mySpeed = 10; //units in metres per second
	int speedOfLight = 299792458;
	double changeFactor = sqrt(1 - (pow(mySpeed,2) / pow(speedOfLight,2)));
	double newSpeed = mySpeed - changeFactor;
	cout << "I am traveling at " << newSpeed << " metres per second!" << endl;
	getchar();
}


The result should be smaller than 10, however, when I run the program in VS2012, the program says relativeSpeed = 9 which can't be correct. (I'm expecting a very long 9.99999999 somewhat sequence)

I am pretty sure that my formula is correct, but how do I get C++ to calculate the correct floating point number?
cout defaults to 6 dp, so try using setprecsion - look it up in the reference section.
Looks legit: http://gm4.in/i/dn9.png
It rounds to 9 because of precision issues.
I suggest to look into changeFactor calculation. You might made mistake there: result of division of two powers is very close to 0, 1-<result> close to one and sqrt(<>) is even closer.
Yeah, now I think about it - you need to set a much higher MySpeed - relativity is only noticeably at very high speed.

Edit: It was MiiNiPaa's comment that made me think about it properly.
Last edited on
Hmm. changeFactor always will be in [0;1]. And that Factor part of the name... I'm sure that you should multiply mySpeed with changeFactor, not substract.

Also include <iomanip> and add << std::setprecision(16) before outputting newSpeed.
I am traveling at 9.999999999999995 metres per second!
Last edited on
Actualy, the problem here is that,
 
(pow(mySpeed,2) / pow(speedOfLight,2))


will always return 0 if mySpeed<speedOfLight.
Last edited on
Nope, pow() always returns floating point values. No integer division here.
Last edited on
Jeah ... my mistake. Just checked the reference and there isn't pow(int,int).
Thanks for all your replies.

cout.precision(16);
has worked for me, but I've reopened VS to check my code again and now cout.precision doesnt work anymore (also setprecision in iomanip doesnt work)
Nevermind, as TheIdeasMan said, 10 metres/second were too slow to make any difference.
Thanks everyone :)
Topic archived. No new replies allowed.