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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With