Page 1 of 1

Finding the root of a univariate function

Posted: Tue Nov 22, 2022 6:50 am
by Fifis
Dear all,

Sorry if it is a duplicate; I posted a similar question to the 'Programming' section, but realised that root finding is a form of estimation. Does EViews have root-finding capabilities for a univariate function (Brent's method, bisecetion, secant, or something similar)?

Simple example: there are monthly data for the levels of some indicator. There are forecast monthly logarithmic growth rates (pre-defined). There is a forecast annual figure for the total monthly sales (i.e. their sum). The goal is to find such a constant that, when added to all monthly growth rates, would produce a series of levels that add up to the annual figure. This is the quick working example in R:

Code: Select all

r <- c(-0.063, 0.018, -0.084,  0.160, 0.033, -0.082, 0.049, 0.074,  0.058, -0.031, 0.151, 0.039)
y.ann.sum.desired <- 15
y <- exp(cumsum(r)) # Levels from log-growth rates
y.ann.sum <- sum(y) # 13.02 -- lower than the desired 15


One can manually fiddle with the values and arrive at an approximate answer.

Code: Select all

sumCorr <- function(x = 0) sum(exp(cumsum(r + x)))
sumCorr(0.01)  # = 13.96, closer to the truth
sumCorr(x = 0.0201)  # = 15.0007, overshoot
sumCorr(x = 0.020093)  # = 14.9999, almost correct


However, there is an immensely helpful function in many packages -- a univariate root solver to find the root of the equation `f(x) = 0` -- in our case, `sum(exp(cumsum(r + x))) - 15 = 0`:

Code: Select all

uniroot(function(x) sumCorr(x) - y.ann.sum.desired, interval = c(0.01, 0.03), tol = 1e-10)
# $root = 0.02009369
sum(exp(cumsum(r + 0.0200936879))) # 15.000000005, great!


I need to implement multiple such corrections in multiple projects in EViews, and am asking what the good way to start would be. (This is a simplified example, which is why analytical solution won't cut it -- the real expressions do not have closed-form solutions.) Any ideas about how to avoid hard-coding the bisection routines and rely on the built-in EViews capabilities?

Many thanks in advance!

Yours sincerly,
Andreï V. Kostyrka

Re: Finding the root of a univariate function

Posted: Tue Nov 22, 2022 11:12 am
by EViews Matt
Hello,

You can use EViews' user-defined optimization feature for this purpose. I've recreated your example as an EViews program below.

Code: Select all

wfcreate u 12
series r
r.fill -0.063, 0.018, -0.084,  0.160, 0.033, -0.082, 0.049, 0.074,  0.058, -0.031, 0.151, 0.039

subroutine local objectiveFunction(scalar !objective, scalar !x, series r, scalar !target)
   series tmp = @exp(@cumsum(r + !x))
   !objective = @pow(@sum(tmp) - !target, 2)
endsub

!objective = 0
scalar x = 0
optimize(min) objectiveFunction(!objective, x, r, 15)

Re: Finding the root of a univariate function

Posted: Mon Nov 28, 2022 1:39 am
by Fifis
Many thanks! This is what I was looking for.