Reputation: 1522
I've a function as follows:
V <- seq(50, 350, by = 1)
> VK
Voltage^0 Voltage^1 Voltage^2 Voltage^3
-1.014021e+01 9.319875e-02 -2.738749e-04 2.923875e-07
> plot(x = V, exp(exp(sapply(0:3, function(x) V^x) %*% VK)), type = "l"); grid()
Now I would like to do an inverse regression upon this certain function. I've seen Solving for the inverse of a function in R :
inverse = function (f, lower = -100, upper = 100) { function (y) uniroot((function (x) f(x) - y), lower = lower, upper = upper)1 }
square_inverse = inverse(function (x) x^2, 0.1, 100)
square_inverse(4)
and I'm trying to adjust it to my purposes as follows:
certain_function <- function(x=V) { exp(exp(sapply(0:3, function(x) V^x) %*% VK)) }
inverse = function (f, lower = 50, upper = 350) {
function (y) uniroot((function (x) f(x) - y), lower = lower, upper = upper)[1]
}
inverse_regression = inverse(certain_function, 50, 350)
inverse_regression(2)
Unfortunately this yields:
Error in uniroot((function(x) f(x) - y), lower = lower, upper = upper) :
f() values at end points not of opposite sign In addition: Warning messages:
1: In if (is.na(f.lower)) stop("f.lower = f(lower) is NA") :
the condition has length > 1 and only the first element will be used
2: In if (is.na(f.upper)) stop("f.upper = f(upper) is NA") :
the condition has length > 1 and only the first element will be used
As far as I understood: The error means that there are more roots than only one (uniroot can only handle one root) but there shouldn't be more than one root since it's a strictly monotonically increasing function. The warnings I do not understand..
edit: I'm trying to get behind it.. I removed both exponentials which yields the following plot:
and this still generates the following error:
> inverse_regression(0.1)
Error in uniroot((function(x) f(x) - y), lower = lower, upper = upper) :
f() values at end points not of opposite sign In addition: Warning messages:
1: In if (is.na(f.lower)) stop("f.lower = f(lower) is NA") :
the condition has length > 1 and only the first element will be used
2: In if (is.na(f.upper)) stop("f.upper = f(upper) is NA") :
the condition has length > 1 and only the first element will be used
Why is this? Obviously the curve has opposite signs at both end points.. I guess end points mean the points left and right to the root?
Upvotes: 1
Views: 206
Reputation: 1522
Probably the inverse regression did not work due to the definition of "certain_function". This is a matrix-vector product and the result is a vector again. Therefore I transformed this to a regular function function(x) exp(exp(sum(x^0*VK[1],x^1*VK[2],x^2*VK[3],x^3*VK[4]))
and now it is working.
Hence, one should be aware of the bounds each time in general.
Upvotes: 0