Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
#include <iomanip>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <vector>
using namespace std;
void usage()
{
cout <<
"Usage: calcres.exe <resval> <numres> <s/p>" << endl <<
"Where: <resval> is the desired resistance" << endl <<
" <numres> is the number of resistors to use" << endl <<
" <s/p> is 's' to use series resistors, or 'p' to use parallel resistors" << endl;
}
float e[25] = {1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2, 1.1, 1.3, 1.6, 2.0, 2.4, 3.0, 3.6, 4.3, 5.1, 6.2, 7.5, 9.1, 10};
void getParallel(float target, int nres, vector<float> ¤t, float currentRecipSum, vector<float> &best, float &bestValue)
{
if(fabs(bestValue - target) / target < 0.001) // 0.1% error is acceptable
return;
if(currentRecipSum > 0 && 1/currentRecipSum < bestValue) // early-out for aimless checks
return;
for(float decade = 0.001; decade <= 1000000; decade *= 10)
{
if(decade * 10 < bestValue) // early-out for aimless checks
continue;
for(int i = 0; i < 25; i++)
{
if(current.size() == nres - 1)
{
float val = 1 / (1/(decade*e[i]) + currentRecipSum);
if(fabs(val - target) < fabs(bestValue - target))
{
bestValue = val;
best = current;
best.push_back(decade*e[i]);
if(fabs(bestValue - target) / target < 0.001)
return;
}
}
else
{
current.push_back(decade*e[i]);
getParallel(target, nres, current, currentRecipSum + 1/(decade*e[i]), best, bestValue);
current.pop_back();
}
}
}
}
int main(int argc, char **argv)
{
if(argc != 4)
{
usage();
return -1;
}
float target = atof(argv[1]);
int nres = atoi(argv[2]);
char sp = argv[3][0];
if(target <= 0 || nres <= 0 || (sp != 's' && sp != 'p'))
{
usage();
return -1;
}
if(sp == 'p')
{
vector<float> best, current;
float bestValue = 0;
getParallel(target, nres, current, 0, best, bestValue);
for(int i = 0; i < best.size(); i++)
cout << "Resistor " << (i+1) << ": \t" << best[i] << endl;
cout << "Parallel total: " << bestValue << endl;
cout << "Error: " << setprecision(2) << ( (bestValue - target) / target * 100 ) << "%" << endl;
}
else
{
cout << "Series calculation not implemented" << endl;
}
return 0;
}
Compiling the source code....
$g++ main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1
Executing the program....
$demo 4684 2 p
Resistor 1: 6800
Resistor 2: 15000
Parallel total: 4678.9
Error: -0.11%
5% resistors would likely have poor temperature stability, making connecting them to meet a 0.1% requirement problematic. At a minimum you should use 1% resistors.Assume E24 (5%).