Proportionately distribute (prorate) a value across a set of values [duplicate]
Possible Duplicate:
Proportionately distribute (prorate) a value across a set of values
I have been looking for an algorithm to distibute the total amount monthly based on the number of days of the year in C# so that the sum of all proportons is equal to the total value.
A date range within a year, and tot开发者_JS百科al amount is given.
Example:
for a value 19550 and date range 9/1/2011 to 6/30/2012
September 1,929.28
October 1,993.59
November 1,929.28
December 1,993.59
January 1,993.59
February 1,864.97 - 28 days
March 1,993.59 - 31 days
April 1,929.28 - 30 days
May 1,993.59
June 1,929.28
but the total is 19,550.04 which is .04 more than the total.
Along with Ricky's answer:
It is not always possible to evenly distribute a given amount over a certain time period. Actually, it is quite rare that an amount is evenly distributed over a given time period.
This is generally accounted for in finance by allowing the last number be less than the average normal number in order to make up the difference.
For example, in your situation the amount for june should be 1929.24.
Generally you keep track of the amount assignment as you are building out the chart. Once you get to the end you have a choice. Either allow the amount to be higher or do one more payment for a much lower amount.
Basically, you need to change your algorithm that generates monthly amounts. Put a check in there to ensure that the amount you calculated is still available. If it's not take the lower of the two values.
It sounds like you already have code for proportional distribution; but you are rounding to the nearest cent, so now all you need is to get the exact sum you want. I have two ideas:
- Simply compute the difference between the total you wanted and the total you got, then add that amount to one of the months
- After computing the value for one month, remove it from the total. For instance, after you compute the value 1929.28 for September, subtract 1929.28 from 19550 and subtract 30 from the number of days. Now your problem changes: instead of distributing 19550 over 9/1/2011 to 6/30/2012, you have to distribute 17620.72 over 10/1/2011 to 6/30/2012. The rounding error will naturally disappear this way, as the final month will get 100% of whatever is left over.
Possible related SO answer: Proportionately distribute (prorate) a value across a set of values
Strange that it has the same title as your question...
精彩评论