2
votes

I have the code below that I am trying to solve with rSymPy. All of the variables in the equation are defined below, except for y -- which I am solving for.

How can I substitute the values for Q, n, m, g, k, and Sf simultaneously in the equation defined below and obtain the value of 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] )")

This is the error that I received from the function call:

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
1
Don't you need sympy to also create the variables? - user3710546
@Pascal Thank you for your suggestion. I went back to the SymPy Tutorial and worked on more examples until I could find a solution to my problem. - iembry

1 Answers

3
votes

The following is the solution that I have come up with:

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