Skip to content

Add escape velocity calculator using standard physics formula #12721

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
May 10, 2025
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
f1a39f3
Added iterative solution for power calculation
SajeevSenthil May 6, 2025
89ad00e
Added iterative solution for power calculation
SajeevSenthil May 6, 2025
ee3f4be
Added iterative solution for power calculation
SajeevSenthil May 6, 2025
a55058b
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] May 6, 2025
1b86189
Added iterative solution for power calculation fixes #12709
SajeevSenthil May 6, 2025
53ca0d3
Merge branch 'optimized-power-iteration' of https://github.com/Sajeev…
SajeevSenthil May 6, 2025
bde1393
Added iterative solution for power calculation FIXES NUMBER 12709
SajeevSenthil May 6, 2025
935febe
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] May 6, 2025
a908d03
Escape velocity is the minimum speed an object must have to break fre…
SajeevSenthil May 10, 2025
3c57056
Merge branch 'optimized-power-iteration' of https://github.com/Sajeev…
SajeevSenthil May 10, 2025
f33964a
Fix: added header comment to escape_velocity.py
SajeevSenthil May 10, 2025
58273e7
Merge branch 'TheAlgorithms:master' into physics
SajeevSenthil May 10, 2025
c6cfddc
Trigger re-PR with a minor change
SajeevSenthil May 10, 2025
5854d54
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] May 10, 2025
fa2597a
Fix: resolve Ruff linter errors and add Wikipedia reference
SajeevSenthil May 10, 2025
f4ea962
Delete maths/power_using_iteration.py
MaximSmolskiy May 10, 2025
a01af96
Test doctests
MaximSmolskiy May 10, 2025
cb9c027
Update escape_velocity.py
MaximSmolskiy May 10, 2025
ad97a08
Update escape_velocity.py
MaximSmolskiy May 10, 2025
1682ad4
Update escape_velocity.py
MaximSmolskiy May 10, 2025
7cceb7e
Update escape_velocity.py
MaximSmolskiy May 10, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions maths/power_using_iteration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
def power(base: float, exponent: int) -> float:
"""
Optimized power function using exponentiation by squaring.

Args:
base (float): The base number.
exponent (int): The exponent.

Returns:
float: The result of base raised to the power of exponent.

Examples:
>>> power(2, 3)
8.0
>>> power(5, -2)
0.04
>>> power(10, 0)
1.0
>>> power(7, 2)
49.0
>>> power(2, -3)
0.125
>>> power(2.5, 4)
39.0625
>>> power(-3.5, 2)
12.25
>>> power(-2, 3)
-8.0
>>> power(0, 5)
0.0
>>> power(0, 1)
0.0
>>> power(0, -1)
Traceback (most recent call last):
...
ZeroDivisionError: 0.0 cannot be raised to a negative power.
>>> power(0, 0)
Traceback (most recent call last):
...
ValueError: 0.0 raised to the power of 0 is indeterminate.
>>> power(1, 1000)
1.0

"""
if base == 0 and exponent == 0:
raise ValueError("0.0 raised to the power of 0 is indeterminate.")
if base == 0 and exponent < 0:
raise ZeroDivisionError("0.0 cannot be raised to a negative power.")

result = 1.0
if exponent < 0:
base = 1 / base
exponent = -exponent
while exponent:
if exponent % 2 == 1:
result *= base
base *= base # Square the base
exponent //= 2 # Halve the exponent
return round(result, 5) # Round to 5 decimal places


if __name__ == "__main__":
import doctest

doctest.testmod()
print("Raise base to the power of exponent using an optimized approach...")

try:
# Input handling and validation
base = float(input("Enter the base: ").strip()) # Supports float & int
exponent = int(
input("Enter the exponent: ").strip()
) # Ensures exponent is an integer

# Calculate result
result = power(base, exponent)

# Display the result
print(f"{base} to the power of {exponent} is {result}")

except ValueError as e:
# Handle invalid input or indeterminate cases
print(e)
except ZeroDivisionError as e:
# Handle division by zero
print(e)
69 changes: 69 additions & 0 deletions physics/escape_velocity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import math


def escape_velocity(mass: float, radius: float) -> float:
"""
Calculates the escape velocity needed to break free from a celestial body's
gravitational field.

The formula used is:
v = sqrt(2 * G * M / R)

where:
v = escape velocity (m/s)
G = gravitational constant (6.67430 * 10^-11 m^3 kg^-1 s^-2)
M = mass of the celestial body (kg)
R = radius from the center of mass (m)

Source:
https://en.wikipedia.org/wiki/Escape_velocity

Args:
mass (float): Mass of the celestial body in kilograms.
radius (float): Radius from the center of mass in meters.

Returns:
float: Escape velocity in meters per second, rounded to 3 decimal places.

Examples:
>>> escape_velocity(5.972e24, 6.371e6) # Earth
11185.978
>>> escape_velocity(7.348e22, 1.737e6) # Moon
2376.307
>>> escape_velocity(1.898e27, 6.9911e7) # Jupiter
60199.545
>>> escape_velocity(0, 1.0)
0.0
>>> escape_velocity(1.0, 0)
Traceback (most recent call last):
...
ZeroDivisionError: Radius cannot be zero.
"""
gravitational_constant = 6.67430e-11 # m^3 kg^-1 s^-2

if radius == 0:
raise ZeroDivisionError("Radius cannot be zero.")
if mass == 0:
return 0.0

velocity = math.sqrt(2 * gravitational_constant * mass / radius)
return round(velocity, 3)


if __name__ == "__main__":
import doctest

doctest.testmod()
print("Calculate escape velocity of a celestial body...\n")

try:
mass = float(input("Enter mass of the celestial body (in kg): ").strip())
radius = float(input("Enter radius from center (in meters): ").strip())

velocity = escape_velocity(mass, radius)
print(f"Escape velocity is {velocity} m/s")

except ValueError:
print("Invalid input. Please enter valid numeric values.")
except ZeroDivisionError as e:
print(e)