From: Ian Jackson Date: Sun, 21 Aug 2016 20:56:56 +0000 (+0100) Subject: compute-scottish-stv: fixes X-Git-Url: http://www.chiark.greenend.org.uk/ucgi/~ian/git?p=appendix-a6.git;a=commitdiff_plain;h=4642960b13763e24dcb10ab40cd650e12e1f84fe;ds=sidebyside compute-scottish-stv: fixes --- diff --git a/compute-scottish-stv b/compute-scottish-stv index d92db96..e09f1eb 100755 --- a/compute-scottish-stv +++ b/compute-scottish-stv @@ -32,6 +32,9 @@ our $stage=0; our $quota; our %tie; +our $DIGS = 5; +our $F = (new Math::BigRat 10)->bpow($DIGS); + open DEBUG, ">.compute.log" or die $!; DEBUG->autoflush(1); @@ -156,6 +159,30 @@ sub sortballots (@) { } } +sub floor ($) { + my ($v) = @_; + $v = new Math::BigRat $v; # we need a copy + return $v->bfloor(); +} + +sub sv ($) { + my ($in) = @_; + my $v = new Math::BigRat $in; # just in case + my $intpart = floor($v); + my $frac = $v - $intpart; + my $good = floor($frac * $F); + my $bad = $frac * $F - $good; + my $s = sprintf "%7d", $intpart; + if ($frac) { + $s .= sprintf ".%0${DIGS}d", $good; + $s .= sprintf "%-4s", ($bad ? "+$bad" : ""); + } else { + $s .= sprintf " %${DIGS}s%4s", '', ''; + } +#print STDERR "# $in => $s # (intpart=$intpart frac=$frac)\n"; + return $s; +} + sub prf { my $fmt = shift; printf "stage %d: ".$fmt, $stage, @_; @@ -172,15 +199,15 @@ sub countballots () { foreach my $c (reverse sort total_history_cmp grep { !$_->{NonCont} } values %cands) { - prf "candidate %-10s: %10s votes\n", $c->{Cand}, $c->{Total}; + prf "candidate %-10s: %s votes\n", $c->{Cand}, sv $c->{Total}; } } sub computequota () { my $totalvalid = 0/1; $totalvalid += $_->{Total} foreach values %cands; - $quota = ($totalvalid / (1 + $seats)) -> bfloor(); - prf "quota %10s\n", $quota; + $quota = floor($totalvalid / (1 + $seats)); + prf "quota %s\n", sv $quota; } sub total_history_cmp () { @@ -304,15 +331,14 @@ for (;;) { my $B = $c->{Total}; my %tspr; - prf "surplus %10s\n", $surplus; + prf "surplus %s\n", sv $surplus; foreach my $v (@{ $c->{Votes} }) { my $previously = $v->{TransferredSurplus}; push @$previously, $c->{Cand}; my $A = $surplus * $v->{Weight}; - my $F = 100000; - my $xfervalue = ((($A * $F) / $B) -> bfloor() ) / $F; + my $xfervalue = floor(($A * $F) / $B) / $F; # SLGEO 48(3): we do arithmetic to 5 d3ecimal places, # but always rounding down votelog $v, "transferring with value $xfervalue (A=$A B=$B)"; @@ -322,8 +348,8 @@ for (;;) { die unless $tspr{"@$previously"} == $xfervalue; } else { $tspr{"@$previously"} = $xfervalue; - prf "transfer value of ballots %s: %10s\n", - "@$previously", $xfervalue; + prf "transfer value of ballots %s: %s\n", + "@$previously", sv $xfervalue; } } sortballots @{ $c->{Votes} };