I have some trouble with my code. I'm trying to calculate the time it takes for two objects in space to collide due to their gravitational pull. I made the code work in python, but can't get it to work in c++. I've discovered that c++ interprets a small value as 0, and thereby no change happens, and the program freezes.
The code:
#include <iostream>
double gamma = 166857 / 2500000000000000, r = 1.5, width = 0.3;
float a1 = 0, a2 = 0, v1 = 0, v2 = 0, dt = 0.1, elapsedTime;
int m1 = 90, m2 = 90;
double acceleration(int m) {
return ((gamma * m) / (r * r));
}
double speed(double a, double v) {
return (a * dt + v);
}
double distance(double a, double v) {
return (a * dt * dt + v * dt);
}
int main()
{
while (r > 2 * width) {
// Represents person 1's acceleration
a1 = acceleration(m2);
//Represents person 2's acceleration
a2 = acceleration(m1);
// Calculates the speeds
v1 = speed(a1, v1);
v2 = speed(a2, v2);
// Changes distance between the two objects
r -= distance(a1, v1) + distance(a2, v2);
// Saves the time it takes for the objects to collide
elapsedTime += dt;
}
std::cout << elapsedTime;
}
If anyone knows why this happens, and has a solution; please let me know. That would be highly appreciated.