Cope 2.5.0
My personal "standard library" of all the generally useful code I've written for various projects over the years
Loading...
Searching...
No Matches
geometry.py
1def absdeg(angle):
2 """ If an angle (in degrees) is not within 360, then this cuts it down to within 0-360 """
3 angle = angle % 360.0
4 if angle < 0:
5 angle += 360
6 return angle
7
8def absrad(angle):
9 """ If an angle (in radians) is not within 2Pi, then this cuts it down to within 0-2Pi """
10 angle = angle % (pi*2)
11 if angle < 0:
12 angle += (pi*2)
13 return angle
14
15def dist(ax, ay, bx, by):
16 return sqrt(((bx - ax)**2) + ((by - ay)**2))
17
18def normalize2rad(a):
19 # while a < 0: a += math.tau
20 # while a >= math.tau: a -= math.tau
21 return a % (PI * 2)
22
23def normalize2deg(a):
24 # while a < 0: a += 360
25 # while a >= 360: a -= 360
26 return a % 360
27
28def constrainToUpperQuadrants(ang, deg=False):
29 if deg:
30 ang = radians(ang)
31 # Oh duh
32 return ang % PI
33
34def negPow(num, exp):
35 """ Raise num to exp, but if num starts off as negative, make the result negative """
36 neg = num < 0
37 return (num**exp) * (-1 if neg else 1)
38
39def round2(num, digits=3, tostr=True, scinot:int=False):
40 try:
41 from sympy.core.evalf import N as evalf
42 num = evalf(num)
43 except ImportError:
44 pass
45
46 try:
47 ans = round(num, digits)
48 except:
49 return '{:1f}'.format(num) if tostr else num
50
51 if scinot:
52 ensureImported('scinot', _as="scinotation")
53 if not tostr:
54 raise TypeError("Can't round using scientific notation and not return a string")
55 return scinotation.format(ans, scinot)
56 else:
57 return '{:1f}'.format(ans) if tostr else ans
58
59def largest_square(n, sideLen=1):
60 """ Take the square root of the input number
61 and round down to the nearest integer
62 """
63 side = int(n ** (sideLen/2))
64 return (side, side)