I have a complicated function that calculates the total value of payments from an account into which deposits are made annually. I'd like to solve the function for a growth rate numerically, but NSolve and FindRoot run for hours without returning a solution. This is the function:
CalcDonation[seed_, growthrate_, reinvestrate_, annualcontrib_, horizon_] :=
Module[{balance = 0, earnings, reinvestamount = 0, donation = 0},
For[year = 1, year <= horizon , year++,
(* No annual contribution in first year *)
balance += If[year == 1, seed, annualcontrib + reinvestamount];
earnings = balance * growthrate;
reinvestamount = earnings * reinvestrate;
donation += earnings *(1 - reinvestrate);
];
donation
];
These are the attempts I have made so far:
FindRoot[CalcDonation[5000, g, 0.50, 1200, 36] == 5000 + 36*1200, {g, 0.05}]
NSolve[CalcDonation[5000, g, 0.50, 1200, 36] == 5000 + 36*1200, g, Reals]
Using Manipulate, I can approximate the answer as 0.0656782 (which is how I decided to use 0.05 as the starting point for FindRoot), but is there a way to solve this equation to a certain precision, besides FindRoot and NSolve? If not, how can I use these functions more effectively?
I'm not sure if this question has an answer that I can apply, since the question applies few details about the asker's situation.
growthrate_?NumericQin place ofgrowthrate_, or passing the optionEvaluated -> False, will allowFindRootto obtain the answer very quickly. To find it to a certain precision, useWorkingPrecision -> prec, whereprecis your desired precision. In this case it is also better to express0.5as1/2and0.05as1/20because the former representations are machine precision numbers, which "poison" the calculation. – Oleksandr R. Dec 10 '12 at 4:43_?NumericQissue yet? I wasn't able to find it after a brief search. This question is well written and demonstrates the issue very clearly without any confounding details, so if not, maybe this can be it. If so I will post an answer rather than the above comment which I made on the assumption that this will eventually be closed as a duplicate and deleted when OP indicates his problem has been solved. – Oleksandr R. Dec 10 '12 at 5:20_?NumericQcalled? A brief search of the documentation doesn't suggest to me why your solution works, which is perhaps why I glossed over the reference to it in the linked question. – John Bensin Dec 10 '12 at 5:34ClearAll[]before evaluating – belisarius Dec 10 '12 at 5:53CalcDonationcontinues indefinitely, and withEvaluated -> True(the default) then it will be called withgin place of a numeric value beforeFindRoothas the opportunity to act on it. And belisarius is right--you probably didn't clear the existing definition before redefining it. If you had, the result should have been returned essentially immediately. – Oleksandr R. Dec 10 '12 at 5:54