在R中获得反转功能

时间:2017-05-27 11:11:42

标签: r

我试图在R中绘制给定函数的反函数

f<-function(x){
if( x>1 || x< -1)
    {
       0
}else{
    0.75*(1-x^2)
}} #densityfunction f

fVec <- Vectorize(f)
F<-function(t){
    integrate(fVec, lower=-1, upper=t)$value
}#integral of f over interval -1,1

FVec<-Vectorize(F) #vectorize F

inverse <- function (f, lower = -1, upper = 1) {
   function (y) uniroot((function (x) f(x) - y), lower = lower, upper = upper)$root
}

Finv = inverse(F, -1, 1)
FinvVec<-Vectorize(Finv) # Vectorize
#plot(FVec, xlim=c(-2, 2)) #plot F
plot(FinvVec, xlim=c(-2, 2)) #plot F inv

我的问题是我收到错误:

Error  in uniroot((function(x) f(x) - y), lower = lower, upper = upper) : 
  f() values at end points not of opposite sign

AFAIK这意味着我的功能没有改变符号。 我问我的导师,他告诉我有一个标志改变,我在这里做错了。但我不知道是什么。你们能帮忙吗?

1 个答案:

答案 0 :(得分:1)

如果您将来自uniroot的{​​{1}}打包,则会在发现错误时继续进行

try

结果图表明它只适用于(0,1)中的x。

inverse <- function (f, lower = -1, upper = 1) {
   function (y) try(uniroot((function (x) f(x) - y), lower = lower, upper = upper)$root)
}

enter image description here