[Python] Solving symbolic sum with symbolic bounds and variables

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    Given the following sample, I'd expect sympy to find that Sum_x = 30, but for some reason this symbol is not expanded at all in the solution

    from sympy import *
    from sympy.abc import i

    # Symbols
    x = IndexedBase('x')
    sum_x = Symbol("Sum_x")
    sym_bound = Symbol("upper_bound")

    concrete_bound = 5
    x_constraints = [Eq(x[idx], idx**2) for idx in range(concrete_bound)]

    sym_bound_eq = Eq(sym_bound, 5)
    equation = Eq(sum_x, Sum(x, (i, 0, sym_bound - 1)).doit())

    solution = solve(x_constraints + [equation, sym_bound_eq])
    print(solution)


    Output:

    {Sum_x: Sum(x, (i, 0, upper_bound - 1)), upper_bound: 5, x[0]: 0, x[1]: 1, x[2]: 4, x[3]: 9, x[4]: 16}


    How to make it expanded ? (Notes: ideally I'd like to avoid substituting sym_bound with its value, and the expressions of x's are not that simple in my real case)

    I got it expanded with this, but it seems verbose and manual:

    print(solution[sum_x]
    .subs(sym_bound, solution[sym_bound])
    .doit()
    .subs([(x, solution[x]) for i in range(solution[sym_bound])]))

    Continue reading...

Compartilhe esta Página