Calculate Taylor Series with rSymPy

I tested the rSymPy R interface on CAS SymPy and it works very well. However, I cannot find the correct syntax for using some of the more complex functions, such as the Taylor series search. For example, I tried the following:

library(rSymPy)
sympy("var('p')")
#
##### Cannot make this work ???
#
sympy("from sympy.mpmath import *")
xt <- sympy("p=taylor(exp, 0, 10)")

But this causes an error:

Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  : 
  SyntaxError: ("no viable alternative at input '='", ('<string>', 1, 8, '__Rsympy= from sympy.mpmath import *\n'))

Any help appreciated.

+4
source share
1 answer

There seems to be no explicit Taylor series, but the series function is available. The following code works:

library(rSymPy)
sympy("var('p')")
sympy("var('x')") # or sympy("x = Symbol('x', real=True)")
#
xt <- sympy("p=series(exp(x), x, 0, 10)") # expand about 0 to 10th order

which gives the answer:

[1] "1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + x**6/720 + x**7/5040 + x**8/40320 + x**9/362880 + O(x**10)"

We can verify this answer by changing the code to:

library(rSymPy)
sympy("var('p')")
sympy("var('x')") # or sympy("x = Symbol('x', real=True)")
#
xt <- sympy("p=series(exp(x), x, 0, 10)") # expand about 0 to 10th order
# Remove order information
xt0 <- sympy("p.removeO()")
# Test results
x <- 1/3
T1 <- eval(parse(text=xt0)) # Evaluate the result, xt0
T2 <- exp(x)                # The correct value
print(T1-T2)                # Print the error

Finally, the error from the series extension:

[1] -4.811929e-12

I hope this is useful for anyone who wants to use the rSymPy R package

+3
source

All Articles