SymPy – Is there a way to write a summation, that has a variable with an incrementing subscript?

Question:

I wanted to write this expression, in code:

x1 + x2 + x3 + x4 + x5

I can currently do this via:

import sympy as sp
x1, x2, x3, x4, x5 = sp.symbols('x1 x2 x3 x4 x5')
x1 + x2 + x3 + x4 + x5

But unfortunately, this doesn’t scale very well, incase I wanted to go from x1 to say, x10,000

Any help would be sincerely appreciated.

I tried using SymPy’s summation function, like this:

summation(x(i), (i, 0, n))

But unfortunately got a TypeError, stating:

'Symbol' object is not callable
Asked By: Programming 55

||

Answers:

Here is a way to write the expression x1 + x2 + x3 + x4 + x5 in a way that scales well to larger numbers of variables, using the sympy module:

import sympy as sp

# Define the variables
x = [sp.symbols('x{}'.format(i)) for i in range(1, 6)]

# Calculate the sum of the variables
result = sum(x)

# Print the result
print(result)

In this code, we use a list comprehension to create a list of Symbol objects representing the variables x1, x2, x3, x4, and x5. We then use the sum function to calculate the sum of the elements in the x list, which is the same as the sum of the x1, x2, x3, x4, and x5 variables. Finally, we print the result of the sum.

To scale this code to a larger number of variables, you can simply change the range in the list comprehension that creates the x list. For example, to calculate the sum of x1 to x10000, you can use the following code:

import sympy as sp

# Define the variables
x = [sp.symbols('x{}'.format(i)) for i in range(1, 10001)]

# Calculate the sum of the variables
result = sum(x)

# Print the result
print(result)

In this code, we create a list of Symbol objects representing the variables x1 to x10000, and then use the sum function to calculate the sum of these variables. We then print the result.

Note that using the sympy module for this type of calculation may not be necessary, and you can simply use the built-in sum function to calculate the sum of a list of numbers. For example, the following code calculates the sum of the numbers from 1 to 10000:

# Define a list of numbers from 1 to 10000
x = list(range(1, 10001))

# Calculate the sum of the numbers
result = sum(x)

# Print the result
print(result)

This code creates a list of numbers from 1 to 10000 using the range function, and then uses the sum function to calculate the sum of these numbers. The result is then printed.

Answered By: HenrikL

You can use a generic IndexedBase symbol with a summation:

>>> i = Symbol('i'); x = IndexedBase('x')
>>> Sum(x[i],(i,1,10))
Sum(x[i], (i, 1, 10))
>>> _.doit()
x[10] + x[1] + x[2] + x[3] + x[4] + x[5] + x[6] + x[7] + x[8] + x[9]
Answered By: smichr