TheAlgorithms/Python · error · ValueError
Source voltage must be positive.
Error message
Source voltage must be positive.
What it means
Thrown by charging_capacitor() in electronics/charging_capacitor.py when source_voltage <= 0. The function models a step-response charge curve V(t) = Vs*(1 - e^(-t/RC)) and requires a strictly positive driving voltage; a non-positive source makes the model (and its 'charging' semantics) invalid.
Source
Thrown at electronics/charging_capacitor.py:61
>>> charging_capacitor(source_voltage=0,resistance=10.0,capacitance=.30,time_sec=3)
Traceback (most recent call last):
...
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 a strictly positive source voltage (e.g. 5.0 or 20.0).
- Use abs() only if you deliberately want magnitude of a bipolar source — otherwise fix the sign upstream.
- Check that you are not passing defaults from an unset config field (0 is the classic default).
Example fix
# before charging_capacitor(source_voltage=-9, resistance=1500, capacitance=30, time_sec=4) # after charging_capacitor(source_voltage=9, resistance=1500, capacitance=30, time_sec=4)
Defensive patterns
Strategy: validation
Validate before calling
if source_voltage <= 0:
raise ValueError("source_voltage must be positive")
v = charging_capacitor(source_voltage, resistance, capacitance, time_sec) Prevention
- Fail on unset config fields instead of letting 0 defaults flow into physics calls.
- Use keyword arguments for the four parameters.
When it happens
Trigger: charging_capacitor(source_voltage=0, resistance=1500, capacitance=30, time_sec=4) or any call with a negative source_voltage.
Common situations: Default-initializing voltage to 0 and forgetting to set it; AC or bipolar sources where a signed instantaneous value can be <= 0; parameter-order mix-ups passing time in the voltage slot.
Related errors
- Capacitor at index {index} has a negative or zero value!
- You cannot supply more or less than 2 values
- Resistance must be positive.
- Capacitance must be positive.
- Source voltage must be positive.
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/b4c59f4f14f630a6.
Report an issue: GitHub.