TheAlgorithms/Python · error · ValueError
Capacitance must be positive.
Error message
Capacitance must be positive.
What it means
Thrown by charging_capacitor() when capacitance <= 0. Capacitance scales the RC time constant; zero or negative capacitance is non-physical for a charging model, so the library refuses it (this is the last of the three sequential guards).
Source
Thrown at electronics/charging_capacitor.py:65
ValueError: Source voltage must be positive.
>>> charging_capacitor(source_voltage=20,resistance=-2000,capacitance=30,time_sec=4)
Traceback (most recent call last):
...
ValueError: Resistance must be positive.
>>> charging_capacitor(source_voltage=30,resistance=1500,capacitance=0,time_sec=4)
Traceback (most recent call last):
...
ValueError: Capacitance must be positive.
"""
if source_voltage <= 0:
raise ValueError("Source voltage must be positive.")
if resistance <= 0:
raise ValueError("Resistance must be positive.")
if capacitance <= 0:
raise ValueError("Capacitance must be positive.")
return round(source_voltage * (1 - exp(-time_sec / (resistance * capacitance))), 3)
if __name__ == "__main__":
import doctest
doctest.testmod()
View on GitHub (pinned to f5988cc097)
Solutions
- Pass capacitance in farads as a positive number (e.g. 30 as in the doctest, or 1e-6 for 1 uF).
- Validate unit conversion before the call; ensure floats, not truncated ints.
- Confirm the earlier guards passed — this error implies source_voltage and resistance were already positive.
Example fix
# before charging_capacitor(source_voltage=30, resistance=1500, capacitance=0, time_sec=4) # after charging_capacitor(source_voltage=30, resistance=1500, capacitance=4.7e-6, time_sec=4)
Defensive patterns
Strategy: validation
Validate before calling
if capacitance <= 0:
raise ValueError("capacitance must be positive farads")
v = charging_capacitor(source_voltage, resistance, capacitance, time_sec) Prevention
- Convert uF/nF/pF to farads with explicit multipliers (1e-6, 1e-9, 1e-12).
- Avoid integer truncation of small fractional farad values.
When it happens
Trigger: charging_capacitor(source_voltage=30, resistance=1500, capacitance=0, time_sec=4) or any negative capacitance value.
Common situations: Unit errors (pF/nF/uF vs F) producing 0 after integer truncation; unset config defaults of 0; passing a component count instead of a farad value.
Related errors
- Source voltage must be positive.
- Resistance must be positive.
- Inductance must be positive.
- Capacitor at index {index} has a negative or zero value!
- You cannot supply more or less than 2 values
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/66c155154bd8f5a5.
Report an issue: GitHub.