Zeeman
Zeeman

Reputation: 47

Python 3 - Electronics Analysis Script

I hope someone can point me in the right direction for a script I want to improve. I am studying electronics and have written some Python script to help with the calculations. I have written and small basic script which assists me in calculating the correct resistor value's for a transistor amplifier.

The problem I have is when the required resistors are calculated, I have values that are not matching the standard resistor values.

For Example:

Standard Resistor Values: 100, 150, 275, 340, 420, 550

The result of the calculation in the script gave me a resistor value of 176.

How could I use Python to select the nearest standard value.

If the calculation was 176 then another line of text would say 'Choose a 150 Resistor for the circuit'

I know I can use lists so I can reference the values but I just need a small sample of how I put the script together to show the actual value then reference the standard values from the list.

Hope this makes sense. Any help much appreciated.

My script is very basic but it does the job. Improvements will come later.

Av = 15
Rc = 3300
Vs = 10
Vc = 6
beta = 100

Re = Rc / Av
Ic = (Vs - Vc) / Rc
Ve = Re * Ic
Vb = Ve + 0.7
Ib = Ic / beta
I2 = 10 * Ib
R2 = Vb / I2
R1 = (Vs - Vb) / (I2 + Ib)

print ('Re =',Re)
print ('Ve =',Ve)
print ('Vb =',Vb)
print ('Ic =',Ic)
print ('Ib =',Ib)
print ('I2 =',I2)
print ('R2 =',R2)
print ('R1 =',R1)

It calculates the voltage and current at each part on the transistor and shows the value required for R2 and R1 based on gain and voltage supplied etc.

Upvotes: 1

Views: 245

Answers (3)

LetzerWille
LetzerWille

Reputation: 5668

def closestToR(l, R):

    from operator import itemgetter     

    tupleList = zip(l,  [ abs(x - R) for x in l ])

    closeToR, delta  = sorted(tupleList, key=itemgetter(1)).pop(0)

    print("R = {}     delta = {}".format(closeToR, delta))     

l = [100, 150, 275, 340, 420, 550]

R = 179

R = 150 delta = 29

Upvotes: 0

Chad S.
Chad S.

Reputation: 6631

Use the bisect module to find the insertion point, then consider 1 less than the insertion point..

from bisect import bisect

def find_closest(v, options):
   i = bisect(options, v)
   if i == len(options):
       return options[-1]
   elif i == 0:
       return options[0]
   else:
       low, high = options[i-1:i+1]
       return low if (high-v) > (v-low) else high

standard_values = [100, 150, 275, 340, 420, 550]
answer = 176
print(find_closest(answer, standard_values))

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799210

3>> import bisect
3>> e12brown = [100, 120, 150, 180, 220, 270, 330, 390, 470, 560, 680, 820]
3>> e12brown[bisect.bisect(e12brown, 170) - 1]
150
3>> e12brown[bisect.bisect(e12brown, 170)]
180

Upvotes: 0

Related Questions