Is there any way for R to solve for the inverse of a given single variable function? The motivation is for me to later tell R to use a vector of values as inputs of the inverse function so that it can spit out the inverse function values.
有没有办法让R求解给定单变量函数的逆?我的动机是让我稍后告诉R使用值向量作为反函数的输入,以便它可以吐出反函数值。
For instance, I have the function y(x) = x^2, the inverse is y = sqrt(x). Is there a way R can solve for the inverse function?
例如,我有函数y(x)= x ^ 2,反函数是y = sqrt(x)。 R有没有办法解决反函数?
I looked up uniroot(), but I am not solving for the zero of a function.
我查找了uniroot(),但我没有解决函数的零点问题。
Any suggestions would be helpful.
任何的意见都将会有帮助。
Thanks!
谢谢!
1 个解决方案
#1
26
What kind of inverse are you finding? If you're looking for a symbolic inverse (e.g., a function y that is identically equal to sqrt(x)) you're going to have to use a symbolic system. Look at ryacas for an R library to connect with a computer algebra system that can likely compute inverses, Yacas.
你发现了什么样的逆转?如果您正在寻找符号反转(例如,函数y与sqrt(x)相同),则您将不得不使用符号系统。查看ryacas的R库以连接计算机代数系统,它可能会计算逆,Yacas。
Now, if you need only to compute point-wise inverses, you can define your function in terms of uniroot as you've written:
现在,如果你只需要计算逐点逆,你可以按照你所写的uniroot来定义你的函数:
> 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)
[1] 1.999976
For a given y
and f(x)
, this will compute x
such that f(x) = y
, also known as the inverse.
对于给定的y和f(x),这将计算x使得f(x)= y,也称为逆。
#1
26
What kind of inverse are you finding? If you're looking for a symbolic inverse (e.g., a function y that is identically equal to sqrt(x)) you're going to have to use a symbolic system. Look at ryacas for an R library to connect with a computer algebra system that can likely compute inverses, Yacas.
你发现了什么样的逆转?如果您正在寻找符号反转(例如,函数y与sqrt(x)相同),则您将不得不使用符号系统。查看ryacas的R库以连接计算机代数系统,它可能会计算逆,Yacas。
Now, if you need only to compute point-wise inverses, you can define your function in terms of uniroot as you've written:
现在,如果你只需要计算逐点逆,你可以按照你所写的uniroot来定义你的函数:
> 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)
[1] 1.999976
For a given y
and f(x)
, this will compute x
such that f(x) = y
, also known as the inverse.
对于给定的y和f(x),这将计算x使得f(x)= y,也称为逆。