Skip to content

Commit f57922a

Browse files
authored
Create potential_energy_2_charges.py
1 parent e9e7c96 commit f57922a

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from __future__ import annotations
2+
3+
k_e = 8.99 * (10**9) # N·m²/C², Coulomb's constant
4+
"""reference:https://phys.libretexts.org/Bookshelves/University_Physics/University_Physics_(OpenStax)/University_Physics_II_-_Thermodynamics_Electricity_and_Magnetism_(OpenStax)/07%3A_Electric_Potential/7.02%3A_Electric_Potential_Energy """
5+
6+
def potential_energy_2_charges(
7+
charge_1: float,
8+
charge_2: float,
9+
distance: float,
10+
) -> float:
11+
"""
12+
Calculate the potential energy due to two charges.
13+
14+
Parameters:
15+
- charge_1 (float): The charge in Coulombs.
16+
- charge_2 (float): The charge in Coulombs.
17+
- distance (float): The distance between the charges in meters.
18+
19+
Returns:
20+
- float: The potential energy.
21+
22+
Raises:
23+
- ValueError: If distance is less than zero.
24+
25+
Examples:
26+
>>> potential_energy_2_charges(1e-6, 1e-6, 0.01)
27+
899000.0
28+
>>> potential_energy_2_charges(2e-6, 3e-6, 0.05)
29+
1078800.0
30+
>>> potential_energy_2_charges(0, 3e-6, 0.05)
31+
0
32+
>>> potential_energy_2_charges(2e-6, 3e-6, 0)
33+
inf
34+
>>> potential_energy_2_charges(2e-6, 3e-6, -0.05)
35+
Traceback (most recent call last):
36+
...
37+
ValueError: Distance cannot be less than zero.
38+
"""
39+
if charge_1 == 0 or charge_2 == 0:
40+
return 0
41+
elif distance == 0:
42+
return float("inf")
43+
elif distance < 0:
44+
raise ValueError("Distance cannot be less than zero.")
45+
else:
46+
potential_energy = k_e * charge_1 * charge_2 / distance
47+
return potential_energy
48+
49+
50+
if __name__ == "__main__":
51+
import doctest
52+
53+
doctest.testmod()

0 commit comments

Comments
 (0)