-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathangle.cpp
145 lines (109 loc) · 2.53 KB
/
angle.cpp
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include "angle.hpp"
#include <cmath>
#ifndef M_TWOPI
#define M_TWOPI (2.0 * M_PI)
#endif
Angle::Angle() : rad_{}
{
}
Angle Angle::radians(double rad)
{
return Angle(rad);
}
Angle Angle::degrees(double deg)
{
return Angle(deg / 360. * M_TWOPI);
}
namespace
{
/// @return Radians in the range 0..2π.
double scale(double rad)
{
while (rad < 0) rad += M_TWOPI;
while (rad >= M_TWOPI) rad -= M_TWOPI;
return rad;
}
} // namespace
Angle::Angle(double rad)
{
rad_ = scale(rad);
}
double Angle::rad() const
{
return rad_;
}
double Angle::deg() const
{
return rad_ * 360. / M_TWOPI;
}
Angle::operator double() const
{
return rad_;
}
Angle & Angle::operator+=(const Angle & other)
{
rad_ = scale(rad_ + other.rad_);
return *this;
}
Angle & Angle::operator-=(const Angle & other)
{
rad_ = scale(rad_ - other.rad_);
return *this;
}
Angle & Angle::operator/=(double denominator)
{
rad_ = scale(rad_ / denominator);
return *this;
}
Angle & Angle::operator%= (const Angle & other)
{
rad_ = scale(fmod(rad_, other.rad_));
return *this;
}
Angle Angle::operator+(const Angle & other) const
{
return Angle(rad_ + other.rad_);
}
Angle Angle::operator-(const Angle & other) const
{
return Angle(rad_ - other.rad_);
}
Angle Angle::operator/(double denominator) const
{
return Angle(rad_ / denominator);
}
Angle Angle::operator%(const Angle & other) const
{
return Angle(fmod(rad_, other.rad_));
}
#ifdef UNITTEST_ANGLE
#include "fcmp.hpp"
#include "xassert.hpp"
int main()
{
xassert(fcmp(Angle(), Angle::radians(0)));
xassert(fcmp(Angle(), Angle::degrees(0)));
Angle a = Angle::radians(M_PI_2);
xassert(fcmp(a, M_PI_2));
xassert(fcmp(a.rad(), M_PI_2));
xassert(fcmp(a.deg(), 90));
xassert(fcmp(Angle::degrees(45) + Angle::radians(M_PI_4), Angle::degrees(90)));
xassert(fcmp(Angle::radians(M_PI) - Angle::degrees(45), Angle::degrees(135)));
xassert(fcmp(Angle::degrees(135) / 3., Angle::degrees(45)));
xassert(fcmp(Angle::degrees(135) / 3., Angle::degrees(45)));
xassert(fcmp(Angle::degrees(365) % Angle::degrees(45), Angle::degrees(5)));
a = Angle::degrees(90);
xassert(fcmp(a.rad(), M_PI_2));
a += Angle::radians(M_PI_2);
xassert(fcmp(a, M_PI));
xassert(fcmp(a.rad(), M_PI));
xassert(fcmp(a.deg(), 180));
a -= Angle::radians(M_PI_4);
xassert(fcmp(a.deg(), 135));
a /= 3;
xassert(fcmp(a.deg(), 45));
a += Angle::degrees(90);
a %= Angle::radians(M_PI_2);
xassert(fcmp(a.deg(), 45));
}
#endif