resistors functions
#include <iostream>
using namespace std;
void resistorDemo() {
cout << serial (3, 5) << endl;
cout << serial (3.3, 5.5, 8.8) << endl;
cout << parallel (3, 5) << endl;
cout << parallel (3.3, 5.5, 8.8, 10) << endl;
cout << serial (3, parallel(5, 7, serial(9, 50)), 8, parallel(3, 5)) << endl;
cout << parallel2 (3, 5) << endl;
cout << parallel2 (3.3, 5.5, 8.8, 10) << endl;
}
Things to learn
serial uses default parameters to support from 2 to 4 resistors.
note that serial calculation is to sum up all resistors, so default value of 0 works perfectly.
parallel uses the same method, except that the default value needs to be "infinity". But, what is infinity in programming? In our example, our INFINITY is not really infinity. We just define INFINITY as a "marker" and then check inside the function code to see if the parameter is changed or not. That's why it takes some effort inside the code to distinguish them.
Alternatively, parallel2 accomplish the same thing with multiple routines. It is made possible by "function overloading".
We could use FLT_MAX to approximate infinity (similar to statistics example). The parallel function will be similar to serial.
float parallel ( float a, float b, float c=FLT_MAX, float d=FLT_MAX) {
return 1/ ((1/a)+(1/b)+(1/c)+(1/d));
}
Combinations of functions, like serial (3, parallel(5, 7, serial(9, 50)), 8, parallel(3, 5)), are useful, especially suitable for resistor networks. Encourage you to try various combinations to solve real problems.
More
Can you do functions for LC circuit? low pass filter? high pass filter?