Learn / Worked program
RC Capacitor Charging
Map a first-order physical model to a finite table
What you will learn
- Console streams and complete-line input/outputProgram-local teaching concept
- Finite double arithmetic, precision and round-offValues and typesProgram-local teaching concept
- Parameters, cohesive calculation functions and return valuesLearn conceptFunctions as interfaces
- Physical quantities, conversions and dimensionally consistent modelsProgram-local teaching concept
- Persistent stream formats and per-field width/precisionProgram-local teaching concept
- Finite iteration domains and termination conditionsDecisions and repetitionProgram-local teaching concept
- Aliases for mutable or read-only existing objectsLearn conceptPointers and references
- Transcendental functions and their numerical domainsProgram-local teaching concept
- Complete-line parsing, bounded input and EOF terminationDebugging and code qualityProgram-local teaching concept
- Value parameters, caller inputs and calculation contractsLearn conceptFunctions as interfaces
The complete source
main.cpp
#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
// Read one whole line so a failed conversion cannot trap the input stream.
bool readNumber(const std::string& prompt, double& value, double low, double high) {
std::string line;
while (std::cout << prompt && std::getline(std::cin, line)) {
std::istringstream input(line);
char extra = '\0';
if (input >> value && !(input >> extra) && std::isfinite(value)
&& value >= low && value <= high) {
return true;
}
std::cout << "Enter a finite number in [" << low << ", " << high << "].\n";
}
std::cerr << "Input ended before a valid number was supplied.\n";
return false;
}
double capacitorVoltage(double supplyVolts, double timeSeconds, double tauSeconds) {
// expm1(z) computes exp(z)-1 accurately even when z is close to zero.
return -supplyVolts * std::expm1(-timeSeconds / tauSeconds);
}
int main() {
double resistanceOhms = 0.0, capacitanceMicrofarads = 0.0, supplyVolts = 0.0;
if (!readNumber("Resistance (ohms): ", resistanceOhms, 1e-3, 1e9)
|| !readNumber("Capacitance (microfarads): ", capacitanceMicrofarads, 1e-6, 1e6)
|| !readNumber("Supply voltage (V): ", supplyVolts, 0.0, 1e6)) return 1;
const double capacitanceFarads = capacitanceMicrofarads * 1e-6;
const double tauSeconds = resistanceOhms * capacitanceFarads;
std::cout << std::fixed << std::setprecision(9)
<< "Time constant (s): " << tauSeconds << '\n'
<< "multiple time_s voltage_V\n";
for (int multiple = 0; multiple <= 5; ++multiple) {
const double timeSeconds = multiple * tauSeconds;
std::cout << multiple << ' ' << timeSeconds << ' '
<< capacitorVoltage(supplyVolts, timeSeconds, tauSeconds) << '\n';
}
}
Source integrity
SHA-256 14911ad8ed3e95bf691ece26502d4ecd6692dc278cdfbd6f34d85acd3a6a6c85. Display, copy and approved download use the same source.
What it does and why it was selected
This lab is a particularly strong bridge between engineering and code: a unit conversion defines a time constant, an exponential model predicts a voltage, and a loop shows the response at meaningful multiples of that constant. The historical microfarad conversion is correct; the important changes are validation, naming, and accurate evaluation near time zero.
Actual execution
main reads resistance in ohms, capacitance in microfarads and supply voltage in volts. It immediately converts capacitance to farads using 1e-6. Multiplication by resistance creates tauSeconds. The loop runs integer multiples 0..5 inclusive, giving six rows. Each multiple determines timeSeconds=multiple*tauSeconds; capacitorVoltage then evaluates the charging response for that time and returns a double. For 1000 ohms and 1 microfarad, tau is 0.001 s; at one tau the 5-V supply produces about 3.160602794 V. The actual transcript is stored separately and bound to the tested source hashes.
Mathematical or state model
For an initially uncharged ideal capacitor connected through an ideal resistor to a constant ideal voltage source, tau=RC and Vc(t)=Vs(1-exp(-t/tau)). Ohms times farads give seconds. Differentiating the response gives dVc/dt=(Vs/tau)*exp(-t/tau), so initial slope is finite and positive for a positive supply. At zero time, Vc=0; at one tau, the normalized response is 1-exp(-1), approximately 0.63212; at five tau it is approximately 0.99326. Five time constants do not mean exactly full voltage.
Design and C++ mechanics
The mathematical function receives all its inputs explicitly and knows nothing about prompts or table formatting. This makes it independently reusable at arbitrary nonnegative times. std::expm1 computes exp(z)-1 directly, avoiding cancellation when subtracting a value very close to one. The leading minus changes expm1(-t/tau) into the charging fraction. The current table uses whole tau multiples, where cancellation is modest, but the function is still useful if a later table adds tiny fractions of tau. Physical unit names prevent the input capacitance from being interpreted as farads accidentally.
Historical differences and limits
The input bounds establish positive nonzero R and C; otherwise t/tau could be undefined at the first row. The historical zero-R run printed invalid numerical values rather than a meaningful circuit response. This model omits source impedance, leakage, capacitor tolerance, voltage dependence, temperature dependence and any nonzero initial capacitor voltage. It predicts a continuous analytic response; it is not a time-stepped circuit solver. Zero supply is allowed and tested: every voltage row must then be zero. Scientific or adaptive formatting would be preferable if extending tau far below the nine-decimal display resolution.
Useful extensions
Generalize to Vc(t)=Vs+(V0-Vs)*exp(-t/tau) by adding an initial-voltage argument. Compare charging and discharging with the same function rather than creating incompatible sign conventions. A numerical Euler-method companion would be valuable only if it explains error, time-step stability and convergence against this analytic solution. Do not call the present six-row table a numerical integration.
Source-linked explanations
Follow each line reference to its marked source region. The explanations below are bound to the reviewed source hash and preserve the supplied teaching layers.
Input contract and end-of-file
main.cpp, lines 8–21 →Only validated finite numbers are allowed to reach the RC Capacitor Charging calculation.
- Technical explanation
- getline consumes a complete line, then a temporary istringstream attempts the numeric conversion. After conversion, trying to extract extra detects a trailing non-whitespace character. Failure of that second extraction means no unwanted data remains. The local stream can fail without putting cin into the historical repeated-failbit state. A fresh local stream is created for every attempt. Low/high comparisons establish the caller’s domain, and exhausting cin ends the while condition and returns false.
- Syntax
- The && operators evaluate left to right and short-circuit: range tests run only after numeric extraction succeeds. !(input >> extra) intentionally treats no remaining non-whitespace character as success. A double& or int& parameter writes the accepted value into the caller’s variable.
- Effect on the program
- The caller checks the returned bool and returns exit status 1 on EOF before calculation. Rejected lines are followed by another prompt; valid lines reach the model exactly once.
- Common mistake
- Clearing a permanently exhausted input stream and retrying cannot create new input. Accepting a numeric prefix such as 550x would silently change the input contract.
- Deeper connection
- Reliable input separates parsing from physical or algorithmic validity: a valid number still must lie in this program’s supported domain.
An accurate charging fraction
main.cpp, lines 23–26 →expm1(z) returns exp(z)-1.
- Technical explanation
- expm1(z) returns exp(z)-1. With z=-t/tau, negating it produces 1-exp(-t/tau). Multiplication by supplyVolts scales that dimensionless fraction into volts. The helper returns a value and does not print, enabling both a table and future curve evaluation.
- Syntax
- The helper returns a value and does not print, enabling both a table and future curve evaluation.
- Effect on the program
- The helper returns a value and does not print, enabling both a table and future curve evaluation.
- Common mistake
- Replacing expm1 with an unrelated exponent sign produces exponential growth rather than charging. Zero tau violates the division’s domain.
- Deeper connection
- Read the program’s mathematical or state model
Microfarads are not farads
main.cpp, lines 33–37 →Multiplication by 1e-6 converts the input’s microfarad count to SI farads exactly as a scale conversion, subject to floating rounding.
- Technical explanation
- Multiplication by 1e-6 converts the input’s microfarad count to SI farads exactly as a scale conversion, subject to floating rounding. resistanceOhms*capacitanceFarads then defines tauSeconds. The archive already performed this conversion; modernization makes the unit-bearing names explicit.
- Syntax
- The archive already performed this conversion; modernization makes the unit-bearing names explicit.
- Effect on the program
- The archive already performed this conversion; modernization makes the unit-bearing names explicit.
- Common mistake
- Forgetting 1e-6 stretches the time scale by a million. Do not report this as a historical formula correction because the lab already had it.
- Deeper connection
- Read the program’s mathematical or state model
Six evaluations of an analytic solution
main.cpp, lines 38–43 →Integer multiple values 0,1,2,3,4,5 are converted into times by multiplication with tau.
- Technical explanation
- Integer multiple values 0,1,2,3,4,5 are converted into times by multiplication with tau. Each voltage is evaluated independently from the analytic function. A row is not calculated from the preceding row’s voltage, so this is sampling rather than numerical integration.
- Syntax
- A row is not calculated from the preceding row’s voltage, so this is sampling rather than numerical integration.
- Effect on the program
- A row is not calculated from the preceding row’s voltage, so this is sampling rather than numerical integration.
- Common mistake
- Calling a printed table a time-step simulation suggests accumulated integration error that this program does not have.
- Deeper connection
- Read the program’s mathematical or state model
Recorded input and output
Captured from the compiled canonical program in the supplied verification package. These are recorded terminal sessions, not an interactive browser runner.
Sample run
- Arguments
None- Recorded exit status
- 0
Program input
1000 1 5
Program output
Resistance (ohms): Capacitance (microfarads): Supply voltage (V): Time constant (s): 0.001000000 multiple time_s voltage_V 0 0.000000000 0.000000000 1 0.001000000 3.160602794 2 0.002000000 4.323323584 3 0.003000000 4.751064658 4 0.004000000 4.908421806 5 0.005000000 4.966310265
4 more recorded behavior and error cases
zero supply
- Arguments
None- Recorded exit status
- 0
Program input
1000 1 0
Program output
Resistance (ohms): Capacitance (microfarads): Supply voltage (V): Time constant (s): 0.001000000 multiple time_s voltage_V 0 0.000000000 0.000000000 1 0.001000000 0.000000000 2 0.002000000 0.000000000 3 0.003000000 0.000000000 4 0.004000000 0.000000000 5 0.005000000 0.000000000
different tau
- Arguments
None- Recorded exit status
- 0
Program input
2000 2 3
Program output
Resistance (ohms): Capacitance (microfarads): Supply voltage (V): Time constant (s): 0.004000000 multiple time_s voltage_V 0 0.000000000 0.000000000 1 0.004000000 1.896361676 2 0.008000000 2.593994150 3 0.012000000 2.850638795 4 0.016000000 2.945053083 5 0.020000000 2.979786159
zero R recover
- Arguments
None- Recorded exit status
- 0
Program input
0 1000 1 5
Program output
Resistance (ohms): Enter a finite number in [0.001, 1e+09]. Resistance (ohms): Capacitance (microfarads): Supply voltage (V): Time constant (s): 0.001000000 multiple time_s voltage_V 0 0.000000000 0.000000000 1 0.001000000 3.160602794 2 0.002000000 4.323323584 3 0.003000000 4.751064658 4 0.004000000 4.908421806 5 0.005000000 4.966310265
eof
- Arguments
None- Recorded exit status
- 1
Program input
No standard input.
Program output
Resistance (ohms):
Error output
Input ended before a valid number was supplied.
Build and run
From this folder, with a configured C++17 compiler:
g++ -std=c++17 -Wall -Wextra -Wpedantic main.cpp -o program
./programOn Windows GCC, build with -o program.exe and use .\program.exe. These are desktop examples; VS Code is an editor, the compiler builds an executable, and the terminal runs it.
Windows run command from the supplied metadata: .\program.exe.
Desktop compiler setup and platform limits. How headers and translation units fit together.
Verification and provenance
- Source inspected
- Compile verified
- Warning reviewed
- Behavior verified
- Sanitizer checked
Supplied evidence: 5 recorded behavior/error cases and 5 address/undefined-behavior sanitizer cases for this exact source. These are tested cases, not an exhaustive correctness claim.
Recorded compiler: g++ (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0.
LeakSanitizer: disabled because unavailable under runtime tracing. Windows/MSVC and macOS execution are not certified by this evidence.
Source origin and publication treatment
Modernized user supplied source
User-supplied origin; no independent authorship or license determination. Instructor code is not included.
New or rewritten source, limited sanitized historical excerpts when useful
No new license is asserted by this publication.