- #1
Robin04
- 260
- 16
Hi,
I made a small program that simulates the motion of a body attached to an ideal spring and released from a horizontal position. Some more info here (especially #1 and #3): https://www.physicsforums.com/threads/equations-of-motion-unsolvable-with-elementary-method.827826/
I've been thinking a lot, I've already checked several times my equations and my code but I don't know what's wrong. The body just flies away to the other side of the Sun. :D
Do you have any idea what's the problem with my code?
I made a small program that simulates the motion of a body attached to an ideal spring and released from a horizontal position. Some more info here (especially #1 and #3): https://www.physicsforums.com/threads/equations-of-motion-unsolvable-with-elementary-method.827826/
I've been thinking a lot, I've already checked several times my equations and my code but I don't know what's wrong. The body just flies away to the other side of the Sun. :D
Do you have any idea what's the problem with my code?
Code:
#include <iostream>
#include <math.h>
#include <fstream>
using namespace std;
int main()
{
float x = 0.0f, y = 0.0f,
v_x = 0.0f, v_y = 0.0f,
a_x = 0.0f, a_y = 0.0f,
D = 0.0f, L = 0.0f, m = 0.0f,
dt = 0.0f, T = 0.0f, t = 0.0f, alpha = 0.0f, F = 0.0f;
ofstream File;
cout << "D = ";
cin >> D;
cout << "L = ";
cin >> L;
cout << "m = ";
cin >> m;
cout << "dt = ";
cin >> dt;
cout << "T = ";
cin >> T;
File.open("Coordinates.txt", ios::out);
File << "D = " << D << "\tL = " << L << "\tm = " << m << "\tdt = " << dt << "\tT = " << T << endl;
x = L; // The pendulum starts from a horizontal position; y = 0
while (t <= T)
{
if (y != 0)
alpha = atan2(x, y); //avoiding dividing by 0
else
alpha = 3.1415f / 2.0f; //if y = 0, than the angle is 90 degrees
F = D*(hypotf(x, y) - L); //calculating the spring force: D * dl = D * (sqrt(x^2 + y^2) - L)
a_x = F / m * sin(alpha); //calculating the components of the acceleration
a_y = 9.81f - F / m * cos(alpha);
cout << "Alpha = " << alpha*180/3.1415f << endl; //These are for trouble shooting to see what values go wrong, and as everything depends on everything this brought no help
cout << "dl = " << hypot(x, y) << endl;
cout << "F = " << F << endl;
cout << "a_x = " << a_x << endl;
cout << "a_y = " << a_y << endl;
v_x += (a_x * dt); //velocities
v_y += (a_y * dt);
cout << "v_y = " << v_x << endl;
x += (0.5f * a_x * pow(dt, 2) + v_x * dt); //updating the positions
y += (0.5f * a_y * pow(dt, 2) + v_y * dt);
cout << "t = " << t << "\tx = " << x << "\ty = " << y << endl;
File << t << "\t" << x << "\t" << y << endl;
t += dt;
}
File.close();
system("pause");
return 0;
}