-
Notifications
You must be signed in to change notification settings - Fork 0
/
charge.py
57 lines (45 loc) · 1.46 KB
/
charge.py
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
import sys
import functools
from distance import euclidean_dist
from Vector import Vector
@functools.total_ordering
class Charge:
def __init__(self, coord, charge):
self._coord = coord
self._charge = charge
def potential_at(self, coord):
COULOMB = 8.99 * 10**9 # N m²/C²
r = euclidean_dist(self._coord, coord)
q = self._charge
if r == 0:
return float('inf') if q >= 0 else float('-inf')
return (COULOMB * q) / r
# FIXME:check the calculations before use...
def potential_vector_at(self, coord):
magnitude = self.potential_at(coord)
delta = Vector(coord) - Vector(self)
return magnitude * delta.direction()
def increase_charge(self, charge):
self._charge += charge
def __iadd__(self, charge):
self.increase_charge(charge)
return self
def __str__(self):
res = '%f at %s' % (self._charge, self._coord)
return res
def __lt__(self, other):
return self._charge < other._charge
def __eq__(self, other):
return self._charge == other._charge
def __iter__(self):
yield from self._coord
if __name__ == "__main__":
x = float(sys.argv[1])
y = float(sys.argv[2])
c = Charge((.51, .63), 21.3)
d = Charge((.51, .63), 21.3)
print(c < d, c <= d, c == d, c >= d, c != d, c > d)
c += .2
print(c)
print(c.potential_at((x, y)))
print(c.potential_vector_at((x, y)))