2017-05-27 157 views
-1

我試圖繪製一個給定函數的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

如果您纏繞呼叫uniroottry,那麼當它發現錯誤

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

結果圖它不斷要表明,它才真正適用於X在(0,1)。

plot(FinvVec, xlim=c(-2, 2)) 

enter image description here

+1

非常感謝您!對於這個noobie問題,我真的很陌生。 –