> static void Main(string[] args) > { > double totalTax, fedTax, provTax; > > > totalTax = 500.00; > > if (TrySolveTaxes(totalTax, out fedTax, out provTax)) > Console.WriteLine("TotalTax= {0} fedTax= {1} provTax= {2}", totalTax, fedTax, provTax); > else > Console.WriteLine("cannot solve"); > > > Console.ReadLine(); > > } > public static bool TrySolveTaxes(double totalTax, out double fedTax, out double provTax) > { > bool success = false; > > double fedPortion = .05; > double provPortion = .095; > > // first shot > double amount = Math.Round(totalTax / (fedPortion * provPortion + fedPortion + provPortion), 2); > fedTax = Math.Round(amount * fedPortion, 2) ; > provTax = Math.Round((amount + fedTax) * provPortion, 2) ; > > > int deltaSign = Math.Sign(totalTax - (fedTax + provTax)); > > if (deltaSign == 0) > success = true; > else > { > double direction = .01 * deltaSign; > int oldDeltaSign = deltaSign; > > do > { > amount += direction; > fedTax = Math.Round(amount * fedPortion, 2); > provTax = Math.Round((amount + fedTax) * provPortion, 2); > > deltaSign = Math.Sign(totalTax - (fedTax + provTax)); > provTax = totalTax - fedTax; > > } while (deltaSign == oldDeltaSign); > success = true; > > } > > return success; > } >With this approach, for the totalTax of 74.88$ (correction from the 500.00$ mentioned above BTW), it falls right away in the delta and returns a base amount of 500.03$.
TrySolveTaxes(74.88) Private Function TrySolveTaxes(totalTax As Double) As Boolean Dim fedtax As Double = 0 Dim provtax As Double = 0 Dim success As Boolean = False Dim fedPortion As Double = 0.05 Dim provPortion As Double = 0.095 ' first shot Dim amount As Double = Math.Round(totalTax / (fedPortion * provPortion + fedPortion + provPortion), 2) fedTax = Math.Round(amount * fedPortion, 2) provTax = Math.Round((amount + fedTax) * provPortion, 2) Dim deltaSign As Integer = Math.Sign(totalTax - (fedTax + provTax)) If deltaSign = 0 Then success = True Else Dim direction As Double = 0.01 * deltaSign Dim oldDeltaSign As Integer = deltaSign Do amount += direction fedtax = Math.Round(amount * fedPortion, 2) provtax = Math.Round((amount + fedtax) * provPortion, 2) deltaSign = Math.Sign(totalTax - (fedtax + provtax)) provtax = totalTax - fedtax Loop While deltaSign = oldDeltaSign success = True End If Return success End Function