RC discharge#

A capacitor discharges through a known resistor. The voltage decays exponentially towards a small offset of the measuring device. From the time constant τ = RC we obtain the capacitance.

import numpy as np

import fitwise as fw

rng = np.random.default_rng(3)
t = np.linspace(0, 50, 60)  # ms
voltage = 4.8 * np.exp(-t / 12.5) + 0.12 + rng.normal(0, 0.02, t.size)  # V

model = fw.models.exponential + fw.models.constant
result = fw.fit(model, t, voltage, yerr=0.02)
print(result)
Model:      exponential(x; amp, tau) + constant(x; c)
Method:     Trust Region Reflective (scipy least_squares) (auto: nonlinear)
Converged:  yes (27 evals)
Data:       60 points, yerr given (absolute)
Start:      amp, tau: log-linear fit · c: edge baseline

Parameter    Value   ± Std.Err    Rel.   Bounds
amp          4.794       0.010   0.2 %   –
tau         12.538       0.067   0.5 %   –
c           0.1180      0.0064   5.4 %   –

χ²/ndf = 1.2 (57 dof, p = 0.14)    R² = 0.99971    AIC = 13.8
Correlations > 0.5:  tau–c (-0.83)
Warnings:   none

The Start: line of the report shows how the starting values were found: the offset c from the flat end of the curve (edge baseline), the decay from a log-linear fit of the rest.

fig, axes = result.plot()
axes[0].set_ylabel("U (V)")
axes[1].set_xlabel("t (ms)")
plot 03 rc discharge
Text(0.5, 18.503588541666666, 't (ms)')

Capacitance with R = 10.0 kΩ (assumed exact). τ is in ms, so C comes out in µF.

R = 10.0  # kΩ
tau = result.params["tau"]
print(f"C = {tau.value / R:.4f} ± {tau.stderr / R:.4f} µF")
C = 1.2538 ± 0.0067 µF

Total running time of the script: (0 minutes 0.116 seconds)

Gallery generated by Sphinx-Gallery