Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find roots of the equation in R

Tags:

r

I want to find empirical solution to equation using R.

My function is as follows, where power and flow are vectors:

get.yield.equation <-function(t, power, flow, PV){
sum(flow/((1+t)^power)) - PV # t is a parameter to be calculated
}

where t is a parameter for which I want to find a solution and variables: power, flow, PV are the parameters, which I will pass

For example:

power<-c(0.01549014, 1.01549014)
flow<-c(0.5, 100.5)
PV<-67.07738

The solution that I found is to use uniroot function. It works if I have function with one parameter of interest, but it does not work in my case, where I have additional parameters that define the equation. For example, if I write parameters as constants in my function and pass only parameter of interest that I want to estimate, uniroot gives me a correct solution:

f.ytm<-function(t) {0.5/ (1+t)^(0.01549014)  + 100.5/ (1+t)^(1.01549014) - 67.07738 }
uniroot(f.ytm, interval=c(-1,1), tol= 0.000000000000000001)$root 
[1] 0.5

And the following does not work:

t<-uniroot(get.yield.equation(t, c(0.01549014, 1.01549014), c(0.5, 100.5), 67.07738), interval=c(-1,1), tol= 0.000000000000000001) 
Error in uniroot(get.yield.equation(t, c(0.01549014, 1.01549014), c(0.5,  : 
could not find function "f"

And if I do not pass t, I have the following error:

uniroot(get.yield.equation(c(0.01549014, 1.01549014), c(0.5, 100.5), 67.07738), interval=c(-1,1), tol= 0.000000000000000001)
Error in get.yield.equation(c(0.01549014, 1.01549014), c(0.5, 100.5),  : 
argument "PV" is missing, with no default 

What could be a a solution to get the root of the equation, where constants are passed as parameters?

like image 769
Rfreak Avatar asked Oct 15 '25 09:10

Rfreak


1 Answers

There are ellipses within the function uniroot which can allow it take more parameters for your function:

> get.yield.equation <-function(t, power, flow, PV){
     sum(flow/((1+t)^power)) - PV # t is a parameter to be calculated
 }
> power<-c(0.01549014, 1.01549014)
> flow<-c(0.5, 100.5)
> PV<-67.07738
> uniroot(get.yield.equation, interval=c(-1,1),power=power,flow=flow,PV=PV,tol= 0.000000000000000001)$root 
[1] 0.5
like image 153
KU99 Avatar answered Oct 19 '25 14:10

KU99