#!/usr/bin/perl -w use strict; my @e24 = qw(10 11 12 13 15 16 18 20 22 24 27 30 33 36 39 43 47 51 56 62 68 75 82 91); my @e12 = qw(10 12 15 18 22 27 33 39 47 56 68 82); my @values; my (@all_values, $mult); my ($desired, $first, $second, $combo, $actual, $error, $exact, $is_pv); my (%actual, %error, @sorted, $count, $last_error); @values = @e12; foreach (@ARGV) { if (/e24/i) { print "Using E24 series.\n"; @values = @e24; }; }; for ($mult = 1; $mult < 1E5; $mult *= 10) { foreach (@values) { push @all_values, $_ * $mult; }; }; push @all_values, 1E6; sub pretty_print { my $value = shift; my $ans = $value; if ($value < 1000) { $ans = "${value}R"; } elsif ($value >= 1000 && $value < 10000) { $value =~ /^(\d)(\d)/; $ans = $1 . "K" . $2; } elsif ($value >= 10000 && $value < 1000000) { $ans = ($value / 1000) . "K"; } elsif ($value >= 1000000 && $value < 10000000) { $value =~ /^(\d)(\d)/; $ans = $1 . "M" . $2; } else { $ans = $value; }; $ans =~ s/([KM])0$/$1/i; return $ans; }; print "Enter desired resistance : "; while (!$desired) { $_ = <>; if (/(\d+)R(\d+)/i) { $desired = $1 + ("." . $2); } elsif (/(\d+)K(\d+)/i) { $desired = ($1 + ("." . $2)) * 1000; } elsif (/(\d+)K/i) { $desired = $1 * 1000; } elsif (/(\d+)M(\d+)/i) { $desired = ($1 + ("." . $2)) * 1000000; } elsif (/(\d+)M/i) { $desired = $1 / 1000000; } elsif (/(\d+)/) { $desired = $1; }; }; # Check against preverred values $exact = 0; foreach $first (@all_values) { last if $is_pv; $combo = pretty_print $first; $actual = $first; $actual{$combo} = $actual; $error{$combo} = $error = $actual - $desired; if ($error == 0) { $is_pv = $combo; }; }; # Calculate parallel pairs $exact = 0; foreach $first (@all_values) { last if $exact; foreach $second(@all_values) { last if $exact; last if $second > $first; $combo = (pretty_print $first) . " || " . pretty_print $second; $actual = 1/(1/$first + 1/$second); $actual{$combo} = $actual; $error{$combo} = $error = $actual - $desired; if ($error == 0) { $exact = 1; }; }; }; # Calculate series pairs $exact = 0; foreach $first (@all_values) { last if $exact; foreach $second(@all_values) { last if $exact; last if $second > $first; $combo = (pretty_print $first) . " + " . pretty_print $second; $actual = $first + $second; $actual{$combo} = $actual; $error{$combo} = $error = $actual - $desired; if ($error == 0) { $exact = 1; }; }; }; @sorted = sort {abs $error{$a} <=> abs $error{$b}} keys %error; print "\n"; if ($is_pv) { print "$is_pv is a preferred value!\n"; } else { print "Best ways to make $desired ohms:\n"; $count = 0; $last_error = 0; foreach (@sorted) { last if $count++ > 10; $error = $error{$_}; last if $count > 1 && $last_error == 0 && $error != 0; print "$_ gives $actual{$_} : error = $error\n"; $last_error = $error; }; }; print "\n"; exit;