help-octave
[Top][All Lists]

## Re: Is there a parametric version of fsolve?

 From: Kurt Hornik Subject: Re: Is there a parametric version of fsolve? Date: Mon, 3 Mar 1997 19:03:05 +0100

```>>>>> John W Eaton writes:

> On  2-Mar-1997, Craig Earls <address@hidden> wrote:
> | I have a multivariable function:
> |
> | x=foo(r,s,t)
> |
> | give r and s how can I can find t such that x=0. The order of the
> | arguments is not important, but I need to vary the other parameters so
> | hard coding them in and using fsolve is very inconvenient. Ideally what
> | I would like is something like fsolve, but with extraparameters:
> |
> | fsolve("foo",r,3,5)
> |
> | where 3 and 5 get passed throught to foo, and r is varied to find zero.
> | I am starting to hack fsolve.cc to do this but that looks like a steep
> | climb for a short project, is ther a better way already extant?

> Global variables?

>   function foo (r, s, t)
>     ...
>   endfunction

>   global s = 3;
>   global t = 5;

>   function fsolve_foo (x)

>     global s;
>     global t;

>     foo (x, s, t);

>   endfunction

>   fsolve ("fsolve_foo", r0)

If you don't like global variables, another idea is to use eval to
trick Octave into defining a function inside a function.

Here is something I wrote on this quite a while ago:

Similarly, it is often desired to implement functions which are the
solutions of some equation.  Suppose for example we want to compute the
internal rate of return `R = irr (P, I_0)' of an initial investment I_0
which yields a series (vector) of payments P.  Clearly, R is such that
`npv (R, P, I_0)', the net present value of a series of irregular
(i.e., not necessarily identical) payments P which occur at the ends of
consecutive period, given the initial investment I_0 and the one-period
interest rate R, is zero.

We can thus implement `irr' using `fsolve' for a function `npv' of R
to which P and I_0 are passed as parameters similar to the above.  As P
will in general be a vector and there is no format conversion for
vectors, we first "convert" it to a string containing a pretty-printed
version of its value by `p = type p'.  Hence, `irr.m' could look as
follows.
function r = irr (p, I_0)
n = length (p);
p = type p;
s = ["function npv = f (r); ", ...
"npv = sum (%s .* (1 + r) .^ (-(1:%d))) - %g; ", ...
"endfunction"];
eval (sprintf (s, p, n, I_0));
r = fsolve ("f", 0);
endfunction

Hope this helps.

-k

```