{"record":{"id":"b824ff253ce90a25","repo":"TheAlgorithms/Python","slug":"energy-can-t-be-negative","errorCode":null,"errorMessage":"Energy can't be negative.","messagePattern":"Energy can't be negative\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"physics/mass_energy_equivalence.py","lineNumber":70,"sourceCode":"    in SI units kg from Energy in J.\n\n    energy (float): Mass of body.\n\n    Usage example:\n    >>> mass_from_energy(124.56)\n    1.3859169098203872e-15\n    >>> mass_from_energy(320)\n    3.560480179371579e-15\n    >>> mass_from_energy(0)\n    0.0\n    >>> mass_from_energy(-967.9)\n    Traceback (most recent call last):\n        ...\n    ValueError: Energy can't be negative.\n\n    \"\"\"\n    if energy < 0:\n        raise ValueError(\"Energy can't be negative.\")\n    return energy / c**2\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n","sourceCodeStart":52,"sourceCodeEnd":78,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/physics/mass_energy_equivalence.py#L52-L78","documentation":"Raised by mass_from_energy(energy) when energy is negative; it computes m = E/c^2. Negative energy has no mass equivalent in this classical relation, so it is rejected. Zero energy is valid and returns 0.0.","triggerScenarios":"mass_from_energy(-967.9) from the doctest; passing a signed energy delta (e.g. binding energy reported as negative) instead of its magnitude.","commonSituations":"Binding-energy or potential-energy conventions where released energy is negative; sensor noise producing tiny negative readings near zero; ledger-style sums that go below zero.","solutions":["Pass the magnitude of the energy: abs(energy) when the sign only encodes direction of transfer.","Clamp noisy measurements with max(0.0, energy) before calling.","Wrap in try/except ValueError for user-facing input handling."],"exampleFix":"# before\nmass_from_energy(-967.9)  # ValueError\n\n# after\nmass_from_energy(abs(-967.9))  # 1.076...e-14","handlingStrategy":"validation","validationCode":"energy = max(0.0, energy)  # or abs(energy) if sign encodes transfer direction\nif energy < 0:\n    raise ValueError('energy must be non-negative')\nmass_from_energy(energy)","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Binding-energy conventions often report negative values — take the magnitude.","Clamp noisy near-zero measurements to 0.","energy == 0 is valid and returns 0.0."],"tags":["physics","relativity","input-validation","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}