Ask Your Question

Define truncated power series as two variable function?

asked 2023-08-28 23:51:26 +0100

barrema gravatar image

I'd like to be able to define a function of two variables that involves a sum. My attempt is

x,n,k=var('x n k')
term(k,x) = (-1)^k*1/(2*k+1)*cos((2*k+1)*pi*x/2)
f(m,x) = 4/pi*sum(term(k,x),k,0,m)

When I evaluate the function at any value of m, as above, sagemath doesn't expand the sum, or even evaluate to a number if I enter a value of x. Somehow the sum becomes atomic. Is there a way to make this sort of definition work?

My students naturally constructed truncated power series this way to experiment with in Desmos, and I'd like to bridge that gap into sagemath without Big-O notation or power series rings or anything like that.

edit retag flag offensive close merge delete


Try f(2,x).simplify().

Alternatively you can define f as a Python function and use Python's rather than symbolic sum():

f = lambda m,x: 4/pi*sum(term(k,x) for k in range(m+1))
Max Alekseyev gravatar imageMax Alekseyev ( 2023-08-29 05:07:36 +0100 )edit

These are both marvelously simple solutions. The lambda functions even remains differentiable. If you post this as an answer I'll accept it.

barrema gravatar imagebarrema ( 2023-08-29 21:22:34 +0100 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2023-09-19 04:04:02 +0100

barrema gravatar image

updated 2023-09-19 04:04:27 +0100

As it's been awhile I thought I'd submit Max Alekseyev's comment as an answer so that this question is seen as complete.

The simplify command f(a,x).simplify() does indeed work to evaluate sums inside of symbolic functions. But it seems one has to type the .simplify() method manually each time as it can't effectively be added to the function.

On the other hand, Python's lambda function f = lambda m,x: 4/pi*sum(term(k,x) for k in range(m+1)) evaluates without flaw and seems to retain the advantages of symbolic functions, like differentiability.

edit flag offensive delete link more


Whether it's a lambda function may be inessential here. Definition via def f(m x): ... should work equally well.

Max Alekseyev gravatar imageMax Alekseyev ( 2023-09-19 13:54:38 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2023-08-28 23:51:26 +0100

Seen: 116 times

Last updated: Sep 19 '23