Skip to content

Instantly share code, notes, and snippets.

@bistromath
Created December 12, 2018 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bistromath/bac29f46788dd35f4e90588228145987 to your computer and use it in GitHub Desktop.
Save bistromath/bac29f46788dd35f4e90588228145987 to your computer and use it in GitHub Desktop.
Calculate closest series R pair (or parallel C pair) to a given value
#!/usr/bin/env python
import math
import numpy as np
#calc two series R or two parallel C that produce the closest result
target = int(float(raw_input("Target value: "))*100)
tolerance = float(raw_input("Tolerance (1 or 5): "))
if tolerance == 5:
stdvals = [10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82]
rvals = np.array([int(val) * 10**e for val in stdvals for e in range(0, 8)])
else:
rvals = np.array([round(10.**(i/96.),2) * 10**e for i in range(96) for e in range(1,9)], dtype=int)
nearest=lambda vals,a: min(vals, key=lambda x:abs(x-a))
limitedvals = rvals[rvals <= target]
possiblefirst = limitedvals[limitedvals >= target/2]
options = []
for p in possiblefirst:
possiblesecond = limitedvals[limitedvals<(target-p)]
if len(possiblesecond) == 0:
possiblesecond = [0]
bestsecond = nearest(possiblesecond,target-p)
options = options + [[p,bestsecond,target-(p+bestsecond)]]
optarr = np.array(options)
minerr = np.min(np.abs(optarr[:,2]))
bestoptions = optarr[optarr[:,2] == minerr]
bestoptions = np.array(bestoptions, dtype=np.float64) / 100
for option in bestoptions:
print("%.1f + %.1f = %.1f (error: %.1f/%.2f%%)" % (option[0], option[1], option[0]+option[1], option[2], abs(100*option[2]/float(option[0]+option[1]))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment