Question: public static int calculateEndPopulation ( final int startPopulation, final int maxPopulation, final double growthRate, final int periods ) { if ( periods = = 0

public static int calculateEndPopulation(final int startPopulation,
final int maxPopulation, final double growthRate, final int periods)
{
if (periods ==0)
{
// TODO:
return startPopulation;
}
else
{
// TODO:
// Calculate the end population for the first n-1 periods
// The *start* population for the n'th period is the *end* population for the n-1'th period
int startPopulationForNthPeriod = calculateEndPopulation(startPopulation, maxPopulation, growthRate, periods -1);
// Calculate the growth rate for the n'th period
double newGrowthRate = startPopulationForNthPeriod *(1+ growthRate *(1-(double)startPopulationForNthPeriod / maxPopulation));
// Return the population for the current period
return (int) newGrowthRate;
}
}
I need help figuring out why the code above doesn't pass the code below:
(Hint: make sure all calculations are done with doubles, otherwise there will be rounding errors)
@Test
void testCalculatePopulation()
{
// Note: Populations are whole numbers
// We are using the format:
// calculateEndPopulation(startPopulation, sustainablePpopulation, growthFactor,
// numberOfPeriods)
assertEquals(2000, Recursion.calculateEndPopulation(2000,10000,0.05,0));
assertEquals(2080, Recursion.calculateEndPopulation(2000,10000,0.05,1));
assertEquals(2162, Recursion.calculateEndPopulation(2000,10000,0.05,2));
assertEquals(2246, Recursion.calculateEndPopulation(2000,10000,0.05,3));
assertEquals(2901, Recursion.calculateEndPopulation(2000,10000,0.05,10));
assertEquals(4011, Recursion.calculateEndPopulation(2000,10000,0.05,20));
assertEquals(6448, Recursion.calculateEndPopulation(2000,10000,0.05,40));
assertEquals(8325, Recursion.calculateEndPopulation(2000,10000,0.05,60));
// Population slowly approaching 10000
assertEquals(9318, Recursion.calculateEndPopulation(2000,10000,0.05,80));
assertEquals(9738, Recursion.calculateEndPopulation(2000,10000,0.05,100));
assertEquals(9898, Recursion.calculateEndPopulation(2000,10000,0.05,120));
// But never quite getting to 10000
assertEquals(9980, Recursion.calculateEndPopulation(2000,10000,0.05,1000));
assertEquals(9980, Recursion.calculateEndPopulation(2000,10000,0.05,5000));
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!