MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / center_of_mass

Function center_of_mass

physics/center_of_mass.py:34–104  ·  view source on GitHub ↗

Input Parameters ---------------- particles: list(Particle): A list of particles where each particle is a tuple with it's (x, y, z) position and it's mass. Returns ------- Coord3D: A tuple with the coordinates of the center of mass (Xcm, Ycm, Zcm) rounded to two

(particles: list[Particle])

Source from the content-addressed store, hash-verified

32
33
34def center_of_mass(particles: list[Particle]) -> Coord3D:
35 """
36 Input Parameters
37 ----------------
38 particles: list(Particle):
39 A list of particles where each particle is a tuple with it's (x, y, z) position and
40 it's mass.
41
42 Returns
43 -------
44 Coord3D:
45 A tuple with the coordinates of the center of mass (Xcm, Ycm, Zcm) rounded to two
46 decimal places.
47
48 Examples
49 --------
50 >>> center_of_mass([
51 ... Particle(1.5, 4, 3.4, 4),
52 ... Particle(5, 6.8, 7, 8.1),
53 ... Particle(9.4, 10.1, 11.6, 12)
54 ... ])
55 Coord3D(x=6.61, y=7.98, z=8.69)
56
57 >>> center_of_mass([
58 ... Particle(1, 2, 3, 4),
59 ... Particle(5, 6, 7, 8),
60 ... Particle(9, 10, 11, 12)
61 ... ])
62 Coord3D(x=6.33, y=7.33, z=8.33)
63
64 >>> center_of_mass([
65 ... Particle(1, 2, 3, -4),
66 ... Particle(5, 6, 7, 8),
67 ... Particle(9, 10, 11, 12)
68 ... ])
69 Traceback (most recent call last):
70 ...
71 ValueError: Mass of all particles must be greater than 0
72
73 >>> center_of_mass([
74 ... Particle(1, 2, 3, 0),
75 ... Particle(5, 6, 7, 8),
76 ... Particle(9, 10, 11, 12)
77 ... ])
78 Traceback (most recent call last):
79 ...
80 ValueError: Mass of all particles must be greater than 0
81
82 >>> center_of_mass([])
83 Traceback (most recent call last):
84 ...
85 ValueError: No particles provided
86 """
87 if not particles:
88 raise ValueError("No particles provided")
89
90 if any(particle.mass <= 0 for particle in particles):
91 raise ValueError("Mass of all particles must be greater than 0")

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected