52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
#!/bin/python
|
|
from utils import parse_values
|
|
|
|
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}")
|
|
|
|
def get_ratio():
|
|
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.")
|
|
return desired_ratio
|
|
|
|
def get_inputs():
|
|
raw_input_resistors = input("Enter resistor values separated by spaces or commas: ")
|
|
resistors = parse_values(raw_input_resistors)
|
|
desired_ratio = get_ratio()
|
|
|
|
return (resistors, desired_ratio)
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
resistors, desired_ratio = get_inputs()
|
|
except ValueError as e:
|
|
print(e)
|
|
exit(1)
|
|
find_bests(desired_ratio, resistors)
|
|
|