Skip to content

Commit a908d03

Browse files
committed
Escape velocity is the minimum speed an object must have to break free from a celestial body's gravitational pull without further propulsion.
Takes input as the Mass of the Celestial body (M) and Radius fron the center of mass (M)
1 parent bde1393 commit a908d03

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

physics/escape_velocity.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import math
2+
3+
def escape_velocity(mass: float, radius: float) -> float:
4+
"""
5+
Calculates the escape velocity needed to break free from a celestial body's gravitational field.
6+
7+
The formula used is:
8+
v = sqrt(2 * G * M / R)
9+
where:
10+
v = escape velocity (m/s)
11+
G = gravitational constant (6.67430 × 10^-11 m^3 kg^-1 s^-2)
12+
M = mass of the celestial body (kg)
13+
R = radius from the center of mass (m)
14+
15+
Args:
16+
mass (float): Mass of the celestial body in kilograms.
17+
radius (float): Radius from the center of mass in meters.
18+
19+
Returns:
20+
float: Escape velocity in meters per second, rounded to 3 decimal places.
21+
22+
Examples:
23+
>>> escape_velocity(5.972e24, 6.371e6) # Earth
24+
11185.978
25+
>>> escape_velocity(7.348e22, 1.737e6) # Moon
26+
2376.307
27+
>>> escape_velocity(1.898e27, 6.9911e7) # Jupiter
28+
60199.545
29+
>>> escape_velocity(0, 1.0)
30+
0.0
31+
>>> escape_velocity(1.0, 0)
32+
Traceback (most recent call last):
33+
...
34+
ZeroDivisionError: Radius cannot be zero.
35+
"""
36+
G = 6.67430e-11 # Gravitational constant in m^3 kg^-1 s^-2
37+
38+
if radius == 0:
39+
raise ZeroDivisionError("Radius cannot be zero.")
40+
if mass == 0:
41+
return 0.0
42+
43+
velocity = math.sqrt(2 * G * mass / radius)
44+
return round(velocity, 3)
45+
46+
47+
if __name__ == "__main__":
48+
49+
import doctest
50+
doctest.testmod()
51+
print("Calculate escape velocity of a celestial body...\n")
52+
53+
try:
54+
# User input
55+
mass = float(input("Enter mass of the celestial body (in kg): ").strip())
56+
radius = float(input("Enter radius from center (in meters): ").strip())
57+
58+
# Result
59+
velocity = escape_velocity(mass, radius)
60+
print(f"Escape velocity is {velocity} m/s")
61+
62+
except ValueError:
63+
print("Invalid input. Please enter valid numeric values.")
64+
except ZeroDivisionError as e:
65+
print(e)

0 commit comments

Comments
 (0)