[英]Solving equations in R similar to the Excel solver parameters function
我有一個問題是關於在R中解決函數的可能性,並使用excel做同樣的事情。
但是我想用R來表明R對我的同事來說更好:)
這是等式:
f0<-1e-9
t_pw<-30e-9
a<-30.7397582453682
c<-6.60935546184612
P<-1-exp((-t_pw)*f0*exp(-a*(1-b/c)^2))
我想找到P<-0.5
的b
值。 在Excel中,我們可以通過選擇P值列並將其設置為0.5然后使用求解器參數函數來完成。
我不知道哪種方法最好? 或者其他任何方式嗎?
Thankx。
如果你想解決一個方程式,最簡單的方法就是使用base-R中的uniroot
。
f0<-1e-9
t_pw<-30e-9
a<-30.7397582453682
c<-6.60935546184612
func <- function(b) {
1-exp((-t_pw)*f0*exp(-a*(1-b/c)^2)) - 0.5
}
#interval is the range of values of b to look for a solution
#it can be -Inf, Inf
> uniroot(func, interval=c(-1000, 1000), extendInt='yes')
Error in uniroot(func, interval = c(-1000, 1000), extendInt = "yes") :
no sign change found in 1000 iterations
如您所見,我的單元unitroot
功能失敗。 這是因為你的等式沒有單一的解決方案,也很容易看到。 exp(-0.0000000000030 * <positive number between 0-1>)
實際上(非常接近)1因此你的等式變為1 - 1 - 0.5 = 0
,這是不成立的。 您也可以看到相同的情節:
curve(func) #same result for curve(func, from=-1000, to=1000)
在此函數中,對於任何b,結果將為-0.5。
因此,快速實現這一目標的一種方法是uniroot
但可能是針對不同的等式。
一個工作的例子:
myfunc2 <- function(x) x - 2
> uniroot(myfunc2, interval=c(0,10))
$root
[1] 2
$f.root
[1] 0
$iter
[1] 1
$init.it
[1] NA
$estim.prec
[1] 8
我強烈懷疑你的等式應該包括-t_pw/f0
,而不是-t_pw*f0
,並且t_pw
應該是3.0e-9
,而不是30e-9
。
Pfun <- function(b,f0=1e-9,t_pw=3.0e-9,
a=30.7397582453682,
c=6.60935546184612) {
1-exp((-t_pw)/f0*exp(-a*(1-b/c)^2))
}
然后@ Lyzander的uniroot()
建議工作正常:
u1 <- uniroot(function(x) Pfun(x)-0.5,c(6,10))
這里的估計值是8.05。
par(las=1,bty="l")
curve(Pfun,from=0,to=10,xname="b")
abline(h=0.5,lty=2)
abline(v=u1$root,lty=3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.