如何求解R中给定变量的方程?

Bio*_*eek 4 math r differential-equations

这是方程a <- x * t - 2 * x。我想为 解这个方程t。所以基本上,设置a = 0并求解t。我是R求解方程包的新手。我需要解决复杂根的包。我使用的原始方程有实根和虚根。我只是在寻找代数解决方案,而不是数字解决方案。

我试过:

a <- x * t - 2 * x
solve(a,t)
Run Code Online (Sandbox Code Playgroud)

我遇到了一个错误:

a <- x * t - 2 * x
solve(a,t)
Run Code Online (Sandbox Code Playgroud)

Sté*_*ent 6

You can use Ryacas to get the solution as an expression of x:

library(Ryacas)

x <- Sym("x")
t <- Sym("t")

Solve(x*t-2*x == 0, t)
# Yacas vector:
# [1] t == 2 * x/x
Run Code Online (Sandbox Code Playgroud)

As you can see, the solution is t=2 (assuming x is not zero).

Let's try a less trivial example:

Solve(x*t-2*x == 1, t)
# Yacas vector:
# [1] t == (2 * x + 1)/x
Run Code Online (Sandbox Code Playgroud)

If you want to get a function which provides the solution as a function of x, you can do:

solution <- Solve(x*t-2*x == 1, t)
f <- function(x){}
body(f) <- yacas(paste0("t Where ", solution))$text
f
# function (x) 
# (2 * x + 1)/x
Run Code Online (Sandbox Code Playgroud)


小智 2

您可能正在寻找优化:

a=function(x,t) x*t-2*x
optimize(a,lower=-100,upper=100,t=10)
optimize(a,lower=-100,upper=100,x=2)
Run Code Online (Sandbox Code Playgroud)

如果您需要更多帮助,我需要一个可重现的示例。