[英]Solving equations in R similar to the Excel solver parameters function
I have a question concerning the possibility to solve functions in R, and doing the same using excel. 我有一个问题是关于在R中解决函数的可能性,并使用excel做同样的事情。
However I want to do it with R to show that R is better for my colleagues :) 但是我想用R来表明R对我的同事来说更好:)
Here is the equation: 这是等式:
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))
I want to find the b
value for P<-0.5
. 我想找到
P<-0.5
的b
值。 In Excel we can do it by selecting P value column and setting it to 0.5 and then by using the solver parameters function. 在Excel中,我们可以通过选择P值列并将其设置为0.5然后使用求解器参数函数来完成。
I don't know which method is the best? 我不知道哪种方法最好? Or any other way to do it?
或者其他任何方式吗?
Thankx. Thankx。
If you want to solve an equation the simplest thing is to do is to use uniroot
which is in base-R. 如果你想解决一个方程式,最简单的方法就是使用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
As you see above my unitroot
function fails. 如您所见,我的单元
unitroot
功能失败。 This is because there is no single solution to your equation which is easy to see as well. 这是因为你的等式没有单一的解决方案,也很容易看到。
exp(-0.0000000000030 * <positive number between 0-1>)
is practically (very close to) 1 so your equation becomes 1 - 1 - 0.5 = 0
which doesn't hold. exp(-0.0000000000030 * <positive number between 0-1>)
实际上(非常接近)1因此你的等式变为1 - 1 - 0.5 = 0
,这是不成立的。 You can see the same with a plot as well: 您也可以看到相同的情节:
curve(func) #same result for curve(func, from=-1000, to=1000)
In this function the result will be -0.5 for any b. 在此函数中,对于任何b,结果将为-0.5。
So one way to do it fast, is uniroot
but probably for a different equation. 因此,快速实现这一目标的一种方法是
uniroot
但可能是针对不同的等式。
And a working example: 一个工作的例子:
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
I have a strong suspicion that your equation was supposed to include -t_pw/f0
, not -t_pw*f0
, and that t_pw
was supposed to be 3.0e-9
, not 30e-9
. 我强烈怀疑你的等式应该包括
-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))
}
Then @Lyzander's uniroot()
suggestion works fine: 然后@ Lyzander的
uniroot()
建议工作正常:
u1 <- uniroot(function(x) Pfun(x)-0.5,c(6,10))
The estimated value here is 8.05. 这里的估计值是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.