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
|
from numbers import Number
def clamp(low: Number, high: Number, num: Number) -> Number:
"""Limit range of ``num`` between ``low`` and ``high``"""
return max(low, min(high, num))
def circrect(a: Number, b: tuple[Number, Number], c: tuple[Number, Number]) -> Number:
"""
Calculate the area of the overlap between a circle with radius ``a`` and a
rectangle defined by opposing corner points ``b`` and ``c``.
Args:
a: circle radius
b: first corner coordinate of rectangle
c: second corner coordinate of rectangle (opposite of b)
Returns:
Overlap area (square units)
"""
# normalize input variables
a = abs(a)
b, c = (
(min(b[0], c[0]), min(b[1], c[1])),
(max(b[0], c[0]), max(b[1], c[1])),
)
b = (clamp(-a, a, b[0]), clamp(-a, a, b[1]))
c = (clamp(-a, a, c[0]), clamp(-a, a, c[1]))
return 0
if __name__ == "__main__":
print(
circrect(1, (-1, -1), (1, 1)), # pi
circrect(1, (1, 1), (-1, -1)), # pi
circrect(-1, (-1, -1), (1, 1)), # pi
circrect(2, (10, 10), (11, 11)), # 0
circrect(10, (0, 0), (1, 1)), # 1
)
|