# Why is this loop crashing?

I'm trying to build a method that calculates the internal rate of return http://www.investopedia.com/articles/07/internal_rate_return.asp#axzz1rm5UPp8V when the user taps a button. The cashflows are already stored in NSMutableArray called "cashFlows". Now in the array if I have the values of say -100, 100, 100, 100 with an interest rate of 10% it works fine. But when I have the values of say -5, 100, 100, 100 the program crashes and/or freezes.

I cant seem to figure this out. I'm wondering if the the method is too computational for my computer to handle, seeing that the program could potentially loop through millions of times. Perhaps there's a better way to do this?

-(IBAction) calculateIRR{ double NPV; double rate = 0.1; int period = 1; double tempPV = 0; int count = 0; do{ NPV = 0; period = 1; for (int i=0; i < [cashFlows count]; i++) { double amount = ([[cashFlows objectAtIndex:i] doubleValue]); if(i == 0){ NPV = amount; } else{ tempPV = (amount/pow(1+rate,period)); NPV = tempPV + NPV; period++; } } rate = rate + 0.0000001; count++; } while(NPV > 0); answer.text = [[NSString alloc] initWithFormat:@"%.4f %%", rate * 100]; }

## Answers

With input values of -5, 100, 100, 100, the IRR is 2000%. Your algorithm has to run through the loop 20 Billion times! Maybe at some point you run out of memory, or it just takes a lot of time.

You should use some more efficient numerical algorithm. The simplest I can think of is the Bisection method: http://en.wikipedia.org/wiki/Bisection_method

You have to choose reasonable starting points, but also add a way to modify the starting points if the solution lies outside of the interval (or break the algorithm and exit with a warning about unsuitable input).