-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspring_emulation.cpp
More file actions
81 lines (52 loc) · 2.02 KB
/
Copy pathspring_emulation.cpp
File metadata and controls
81 lines (52 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <cmath>
#include <windows.h>
#define GRAVITY 9.81
#define EPSILON 1e-5
#define FRICTION 0.3
void draw(double position)
{
int screen_pos = static_cast<int>(std::round(position));
for (int i = -20; i < screen_pos; ++i)
std::cout << "-";
std::cout << " []\n";
}
int main()
{
double mass_;
std::cout << "Enter Mass (kg): ";
std::cin >> mass_;
double spring_constant_;
std::cout << "Enter Spring Constant (N/m): ";
std::cin >> spring_constant_;
double displacement_;
std::cout << "Enter Initial Displacement (m): ";
std::cin >> displacement_;
double position_ = displacement_;
double velocity_ = 0.0;
double acceleration_ = 0.0;
double time_ = 0.0;
double dt_ = 0.05;
while (time_ <= 20.0)
{
double spring_acc = -spring_constant_ * position_ / mass_;
int sign_vel = (velocity_ > 0) - (velocity_ < 0);
double friction_acc = -FRICTION * GRAVITY * sign_vel;
double total_acc = spring_acc + friction_acc;
if (std::abs(velocity_) < EPSILON && std::abs(total_acc) < FRICTION * 9.81)
{
velocity_ = 0.0;
acceleration_ = 0.0;
draw(position_);
break;
}
acceleration_ = total_acc;
velocity_ += acceleration_ * dt_;
position_ += velocity_ * dt_;
draw(position_);
Sleep(75);
time_ += dt_;
}
std::cout << "Simulation stopped. Final position: " << position_ << "\n";
return 0;
}