Skip to content

Instantly share code, notes, and snippets.

@hikari-no-yume
Last active March 13, 2019 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hikari-no-yume/445f4ad503b124802230ee0e7fb30262 to your computer and use it in GitHub Desktop.
Save hikari-no-yume/445f4ad503b124802230ee0e7fb30262 to your computer and use it in GitHub Desktop.
Calculate UK or Scottish income tax and find the point where one costs more than the other (https://twitter.com/hikari_no_yume/status/1105922831626502147)
<?php
const UK_2018 = [
0 => 11850,
20 => 46350,
40 => 150000,
45 => INF,
];
const UK_2019 = [
0 => 12500,
20 => 50000,
40 => 150000,
45 => INF,
];
const SC_2018 = [
0 => 11850,
19 => 13850,
20 => 24000,
21 => 43430,
41 => 150000,
46 => INF,
];
const SC_2019 = [
0 => 12500,
19 => 14549,
20 => 24944,
21 => 43430,
41 => 150000,
46 => INF,
];
<?php
const UK_2018 = [
0 => 11850,
20 => 46350,
40 => 150000,
45 => INF,
];
const UK_2019 = [
0 => 12500,
20 => 50000,
40 => 150000,
45 => INF,
];
const SC_2018 = [
0 => 11850,
19 => 13850,
20 => 24000,
21 => 43430,
41 => 150000,
46 => INF,
];
const SC_2019 = [
0 => 12500,
19 => 14549,
20 => 24944,
21 => 43430,
41 => 150000,
46 => INF,
];
function tax(int $annualIncome, array $bands): float {
$tax = 0;
$taxed = 0;
foreach ($bands as $percent => $max) {
if ($annualIncome > $max) {
$tax += ($percent / 100) * ($max - $taxed);
$taxed = $max;
} else {
$tax += ($percent / 100) * ($annualIncome - $taxed);
break;
}
}
return $annualIncome - $tax;
}
function diff(int $annualIncome, array $band1, array $band2): float {
return tax($annualIncome, $band1) - tax($annualIncome, $band2);
}
function findEquilibrium(array $band1, array $band2, float $low, float $high): float {
do {
$avg = ($low + $high) / 2;
$mid = floor($avg);
$lowDiff = diff($low, $band1, $band2);
$midDiff = diff($mid, $band1, $band2);
$highDiff = diff($high, $band1, $band2);
if ($midDiff == 0) {
return $mid;
} else if ($lowDiff == 0) {
return $low;
} else if ($highDiff == 0) {
return $high;
} else if ($lowDiff < 0 && $midDiff < 0) {
if ($highDiff < 0) {
return NAN;
}
$low = $mid;
} else if ($highDiff > 0 && $midDiff > 0) {
if ($lowDiff > 0) {
return NAN;
}
$high = $mid;
} else if (abs($highDiff) < abs($lowDiff)) {
$low = $mid;
} else if (abs($highDiff) > abs($lowDiff)) {
$high = $mid;
} else {
throw new Exception('?');
}
} while(true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment