Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Taylor series using rSymPy

Tags:

r

cas

I have been trying out the R interface rSymPy to the CAS SymPy and it works quite well. However, I cannot find the correct syntax for using some of the more complex features, such as finding a Taylor series. For example, I have 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 it throws the 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.

like image 552
Graham G Avatar asked Sep 30 '22 01:09

Graham G


1 Answers

There does not appear to be an explicit Taylor series available, 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 check this answer by modifying 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 expansion is:

[1] -4.811929e-12

I hope this is helpful to anyone else wishing to use the R package rSymPy

like image 194
Graham G Avatar answered Oct 03 '22 00:10

Graham G