Ask Your Question
0

How to add a condition in the sum function in sage

asked 2024-06-05 01:44:27 +0100

hamouda gravatar image

updated 2024-06-05 15:46:43 +0100

FrédéricC gravatar image

I want to implement the following sum $\sum_{j=0}^{n}a_jx^j$ under the following conditions the coefficient $a_j=j$ if $j $ is even, or $j+1$ otherwise. My problem is how to include these cases in the sum function in sage. Normally the command is sum(a_j*x^j,j,1,n) but how to distinguish between the parity of j ?

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
2

answered 2024-06-05 12:05:45 +0100

rburing gravatar image

Instead of using the symbolic sum that you mention, you can use Python's built-in sum that takes an iterable such as a generator expression:

sage: n = 5
sage: sum((j if j % 2 == 0 else j + 1)*x^j for j in range(1,n+1))
6*x^5 + 4*x^4 + 4*x^3 + 2*x^2 + 2*x
edit flag offensive delete link more

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 2024-06-05 01:44:27 +0100

Seen: 234 times

Last updated: Jun 05