Skip to content

Commit 2f42690

Browse files
committed
optimized math for calculating horizontal line and circle intersection in exercise06 for chapter12
1 parent 3cddb93 commit 2f42690

File tree

1 file changed

+4
-15
lines changed

1 file changed

+4
-15
lines changed

Chapter12/exercises/06/main.cpp

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,14 @@
11
#include "PPP/Simple_window.h"
22
#include "PPP/Graph.h"
33

4-
std::pair<int, int> quadratic_formula(double a, double b, double c) {
5-
int x1 = (-b - std::sqrt(b*b - 4 * a * c) / 2 * a);
6-
int x2 = (-b + std::sqrt(b*b - 4 * a * c) / 2 * a);
7-
return std::make_pair(x1, x2);
8-
}
9-
104
std::pair<int, int> hline_circle_intersection
115
(int y, Point center, int radius) {
12-
using std::pow;
136
// Produce two values!
147
if (y <= center.y - radius || y >= center.y + radius)
158
throw std::runtime_error{"y out of range"};
16-
constexpr double a = 1;
17-
double b = -2 * center.x;
18-
double c = pow(y, 2) + pow(center.x, 2) + pow(center.y, 2)
19-
- pow(radius, 2) - 2 * y * center.y;
20-
return quadratic_formula(a, b, c);
9+
int x1 = center.x + std::sqrt(std::pow(radius, 2) - std::pow(y - center.y, 2));
10+
int x2 = center.x - std::sqrt(std::pow(radius, 2) - std::pow(y - center.y, 2));
11+
return std::make_pair(x1, x2);
2112
}
2213

2314
struct Striped_circle : public Circle {
@@ -28,9 +19,7 @@ struct Striped_circle : public Circle {
2819
for (int y_pos = center.y - radius + spacing;
2920
y_pos < center.y + radius;
3021
y_pos += spacing) {
31-
auto [dx1, dx2] = hline_circle_intersection(y_pos, center, radius);
32-
int x1 = dx1 - center.x;
33-
int x2 = dx2 - center.x;
22+
auto [x1, x2] = hline_circle_intersection(y_pos, center, radius);
3423
stripes.add(Point{x1, y_pos}, Point{x2, y_pos});
3524
}
3625
}

0 commit comments

Comments
 (0)