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>
usingnamespace 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?
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.
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!
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)