|
| 1 | +# Calculate Energy from Mass using Einstein's Mass-Energy Equivalence |
| 2 | + |
| 3 | +# This Python script calculates the energy equivalent of a given mass using Albert Einstein's mass-energy equivalence equation, E=mc². |
| 4 | +# The formula E=mc² states that energy (energy_equivalent) is equal to mass (mass_kg) multiplied by the speed of light (speed_of_light_m_per_s) squared. |
| 5 | + |
| 6 | +# Source: https://en.wikipedia.org/wiki/Mass%E2%80%93energy_equivalence |
| 7 | + |
| 8 | +def calculate_energy_from_mass(mass_kg: float, speed_of_light_m_per_s: float = 299792458) -> float: |
| 9 | + """ |
| 10 | + Calculate the energy equivalent of a given mass using Einstein's mass-energy equivalence equation, E=mc². |
| 11 | +
|
| 12 | + Args: |
| 13 | + mass_kg (float): Mass in kilograms. |
| 14 | + speed_of_light_m_per_s (float): Speed of light in meters per second (default value is the speed of light in a vacuum). |
| 15 | +
|
| 16 | + Returns: |
| 17 | + float: Energy equivalent in joules. |
| 18 | +
|
| 19 | + Examples: |
| 20 | + >>> calculate_energy_from_mass(1) |
| 21 | + 8.987551787368176e+16 |
| 22 | + >>> calculate_energy_from_mass(5, 3e8) |
| 23 | + 1.125937723421022e+18 |
| 24 | + """ |
| 25 | + # Check if the mass is non-negative |
| 26 | + if mass_kg < 0: |
| 27 | + raise ValueError("Mass cannot be negative") |
| 28 | + |
| 29 | + # Check if the speed of light is positive |
| 30 | + if speed_of_light_m_per_s <= 0: |
| 31 | + raise ValueError("Speed of light must be positive") |
| 32 | + |
| 33 | + # Calculate energy using the mass-energy equivalence equation |
| 34 | + energy_equivalent_joules = mass_kg * speed_of_light_m_per_s**2 |
| 35 | + |
| 36 | + # Return the energy equivalent in joules |
| 37 | + return energy_equivalent_joules |
| 38 | + |
| 39 | +if __name__ == "__main__": |
| 40 | + # Import the doctest module to run tests |
| 41 | + import doctest |
| 42 | + |
| 43 | + # Run doctests to verify the function's correctness |
| 44 | + doctest.testmod() |
0 commit comments