initial commit, voltage divider
This commit is contained in:
37
voltage_divider.py
Normal file
37
voltage_divider.py
Normal file
@@ -0,0 +1,37 @@
|
||||
#!/bin/python
|
||||
def find_bests(desired_ratio, resistors):
|
||||
# only keep the 5 best candidates
|
||||
candidates = []
|
||||
|
||||
for R1 in resistors:
|
||||
for R2 in resistors:
|
||||
ratio = R2 / (R1 + R2)
|
||||
error = abs(ratio - desired_ratio)
|
||||
entry = (error, R1, R2, ratio)
|
||||
if len(candidates) < 5:
|
||||
candidates.append(entry)
|
||||
candidates.sort(key=lambda x: x[0])
|
||||
else:
|
||||
if error < candidates[-1][0]:
|
||||
candidates[-1] = entry
|
||||
candidates.sort(key=lambda x: x[0])
|
||||
|
||||
print("Top 5 resistor pairs closest to desired ratio:\n")
|
||||
for i, (error, R1, R2, ratio) in enumerate(candidates, start=1):
|
||||
print(f"{i}. R1 = {R1} Ω, R2 = {R2} Ω -> ratio = {ratio:.6f}, error = {error:.6e}")
|
||||
|
||||
if __name__ == '__main__':
|
||||
raw_input = input("Enter resistor values (floats) separated by spaces or commas: ")
|
||||
resistors = [float(x) for x in raw_input.replace(',', ' ').split() if x.strip()]
|
||||
while True:
|
||||
try:
|
||||
desired_ratio = float(input("Enter desired ratio (0<ratio<=1): "))
|
||||
if 0 < desired_ratio <= 1:
|
||||
break
|
||||
else:
|
||||
print("Invalid ratio.")
|
||||
except ValueError:
|
||||
print("Invalid input.")
|
||||
|
||||
find_bests(desired_ratio, resistors)
|
||||
|
||||
Reference in New Issue
Block a user