简体   繁体   English

在R中求解超越方程

[英]Solving transcendental equations in R

Is there a function for solving transcendental equations in R? 是否有解决R中超越方程的函数?

For example, I want to solve the following equation 例如,我想解决以下等式

x = 1/tan(x)

Any suggestions? 有什么建议么? I know the solution has multiple roots so I also want to be able to recover all the answers for a given interval 我知道解决方案有多个根,所以我也希望能够恢复给定间隔的所有答案

I would plot the function curve and look at it to see what it looks like: 我会绘制函数曲线并查看它以查看它的样子:

R > y = function(x) { x - 1/tan(x) }
R > curve(y, xlim = c(-10, 10))
R > abline(h = 0, color = 'red')

在此输入图像描述

Then I saw there is a root between 0 and 3, I would use uniroot to get the root I want: 然后我看到有一个介于0和3之间的根,我会使用uniroot来获取我想要的根:

R > uniroot(y, interval = c(0, 3))
$root
[1] 0.8603

$f.root
[1] 6.612e-06

$iter
[1] 7

$estim.prec
[1] 6.104e-05

You can use uniroot to find roots of any 1D equations within a given range. 您可以使用uniroot查找给定范围内 uniroot方程的根。 However, getting multiple roots seems like a very hard problem in general (eg see the relevant chapter of Numerical Recipes for some background: chapter 9 at http://apps.nrbook.com/c/index.html ). 然而,获得多个根似乎是一个非常难的问题(例如,请参阅数字食谱的相关章节以获取一些背景:第9章http://apps.nrbook.com/c/index.html )。 Which root is found when there are multiple roots is hard to predict. 当存在多个根时找到哪个根很难预测。 If you know enough about the problem to subdivide the space into subregions with zero or one roots, or if you're willing to divide it into lots of regions and hope that you found all the roots, you can do it. 如果您对问题有足够的了解,可以将空间细分为零或一个根的子区域,或者如果您愿意将其划分为多个区域并希望找到所有根,那么您就可以做到。 Otherwise I look forward to other peoples' solutions ... 否则我期待其他人的解决方案......

In this particular case, as shown by @liuminzhao's solution, there's (at most? exactly?) one solution between n*pi and (n+1)*pi 在这种特殊情况下,如@ liuminzhao的解决方案所示,在n*pi(n+1)*pi之间存在(最多?完全?)一个解决方案

y = function(x) x-1/tan(x)
curve(y,xlim=c(-10,10),n=501,ylim=c(-5,5))
abline(v=(-3:3)*pi,col="gray")
abline(h=0,col=2)

在此输入图像描述

This is a bit of a hack, but it will find roots of your equation (provided they are not too close to a multiple of pi: you can reduce eps if you like ...). 这有点像黑客,但它会找到你的等式的根源(假设它们不是太接近pi的倍数:你可以减少eps如果你喜欢......)。 However, if you want to solve a different multi-root transcendental equation you might need another (specialized) strategy ... 但是,如果你想解决一个不同的多根超越方程,你可能需要另一个(专门的)策略......

f <- function(n,eps=1e-6) uniroot(y,c(n*pi+eps,(n+1)*pi-eps))$root
sapply(0:3,f)
## [1] 0.8603337 3.4256204 6.4372755 9.5293334

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM