TheAlgorithms/Python · error · Exception
Molar mass should be greater than 0 kg/mol
Error message
Molar mass should be greater than 0 kg/mol
What it means
Raised by physics/speeds_of_gas_molecules.py:avg_speed_of_molecule when molar_mass <= 0. Molar_mass appears in the denominator of sqrt(8RT/(pi*M)); zero divides by zero and a negative value yields a complex speed. Like the sibling checks in this file it is a bare Exception, not ValueError.
Source
Thrown at physics/speeds_of_gas_molecules.py:78
>>> avg_speed_of_molecule(273, 0.028) # nitrogen at 273 K
454.3488755062257
>>> avg_speed_of_molecule(300, 0.032) # oxygen at 300 K
445.5257273433045
>>> avg_speed_of_molecule(-273, 0.028) # invalid temperature
Traceback (most recent call last):
...
Exception: Absolute temperature cannot be less than 0 K
>>> avg_speed_of_molecule(273, 0) # invalid molar mass
Traceback (most recent call last):
...
Exception: Molar mass should be greater than 0 kg/mol
"""
if temperature < 0:
raise Exception("Absolute temperature cannot be less than 0 K")
if molar_mass <= 0:
raise Exception("Molar mass should be greater than 0 kg/mol")
return (8 * R * temperature / (pi * molar_mass)) ** 0.5
def mps_speed_of_molecule(temperature: float, molar_mass: float) -> float:
"""
Takes the temperature (in K) and molar mass (in kg/mol) of a gas
and returns the most probable speed of a molecule in the gas (in m/s).
Examples:
>>> mps_speed_of_molecule(273, 0.028) # nitrogen at 273 K
402.65620702280023
>>> mps_speed_of_molecule(300, 0.032) # oxygen at 300 K
394.8368955535605
>>> mps_speed_of_molecule(-273, 0.028) # invalid temperature
Traceback (most recent call last):
...
Exception: Absolute temperature cannot be less than 0 KView on GitHub (pinned to f5988cc097)
Solutions
- Pass molar mass in kg/mol - N2 is 0.028, O2 is 0.032, CO2 is 0.044; divide g/mol values by 1000.
- Validate molar_mass > 0 before the call, especially when it comes from a species lookup that can return 0/None.
- Because this is a bare Exception, catch Exception (and check the message) or pre-validate rather than expecting ValueError.
- Guard gas-name-to-molar-mass mappings with a KeyError/None check so unknown species never reach this function as 0.
Example fix
# before
avg_speed_of_molecule(273, 0) # missing lookup -> 0
# after
MOLAR_MASS_KG = {'N2': 0.028, 'O2': 0.032, 'CO2': 0.044}
m = MOLAR_MASS_KG[gas] # KeyError surfaces the real problem
if m <= 0:
raise ValueError(f'bad molar mass for {gas!r}')
avg_speed_of_molecule(273, m) Defensive patterns
Strategy: validation
Validate before calling
if molar_mass is None or molar_mass <= 0:
raise ValueError(f'molar_mass must be > 0 kg/mol, got {molar_mass!r}')
v = avg_speed_of_molecule(temperature, molar_mass) Type guard
def is_valid_molar_mass_kg(m: float) -> bool:
return isinstance(m, (int, float)) and 0 < m < 1.0 # kg/mol values are < 1 Try / catch
try:
avg_speed_of_molecule(t, m)
except Exception as e:
if 'Molar mass' in str(e):
... Prevention
- Keep molar masses in kg/mol (0.028 for N2); a value > 1 usually means g/mol slipped in.
- Make species lookups raise KeyError instead of returning 0.
- Catch Exception (not ValueError) around this module's calls.
When it happens
Trigger: Calling avg_speed_of_molecule(273, 0) or with a negative second argument, e.g. avg_speed_of_molecule(273, -0.028).
Common situations: Passing molar mass in g/mol (28) instead of kg/mol (0.028) usually gives a wrong but non-raising answer, while passing 0 happens when a lookup table misses the gas; using an atomic mass for a diatomic gas without multiplying by 2 and hitting an uninitialized 0 default; parsing failures that yield 0 for unknown species strings.
Related errors
- Absolute temperature cannot be less than 0 K
- Expected b_coeffs to have {self.order + 1} elements for {sel
- k must not be negative
- Input value must be a positive integer
- Donor concentration should be greater than intrinsic concent
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/a4c614376254fc69.
Report an issue: GitHub.