我有以下代码,我试图用rSymPy
来解决。等式中的所有变量都定义如下,除了y
- 我正在解决这个问题。
如何在等式中同时替换Q
,n
,m
,g
,k
和Sf
的值定义如下并获得y
?
Q <- 1.2
n <- 0.045
m <- 3.4
g <- 9.806
k <- 1
Sf <- 0.2
library(rSymPy)
sympy("solve( [ Eq(n*Q*(2*y*sqrt(1+m**2))**(2/3) - k*(m*y**2)**
(5/3)*sqrt(Sf), 0)], [y] )")
这是我从函数调用中收到的错误:
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl, :
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'n' is not defined
答案 0 :(得分:2)
以下是我提出的解决方案:
library(rSymPy)
Q <- Var("Q")
n <- Var("n")
m <- Var("m")
g <- Var("g")
k <- Var("k")
Sf <- Var("Sf")
y <- Var("y")
sympy("expr = n*Q*(2*y*sqrt(1+m**2))**(2/3) - k*(m*y**2)**(5/3)*sqrt(Sf)")
# [1] "Q*n - k*m*Sf**(1/2)*y**2"
sympy("solve(expr.subs([(Q, 1.2), (n, 0.045), (m, 3.4), (Sf, 0.2), (g, 9.806), (k, 1)]), y)")
# [1] "[-0.188451640531767, 0.188451640531767]"
# This is the answer that I am referring to (above)
out <- sympy("solve(expr.subs([(Q, 1.2), (n, 0.045), (m, 3.4), (Sf, 0.2), (g, 9.806), (k, 1)]), y)")
out <- as.numeric(unlist(strsplit(gsub("\\[|\\]", "", out), ",")))
length(out)
# [1] 2
out
# [1] -0.1884516 0.1884516