Solve equation with sum and index using Sympy
Asked Answered
C

1

6

After having tried many things, I thought it would be good to ask on SO. My problem is fairly simple: how can I solve the following equation using Sympy?

Equation

I want to solve this for lambda_0 and q is an array of size J containing elments between 0 and 1 that sum op to 1 (discrete probability distribution). I tried the following:

from sympy.solvers import solve
from sympy import symbols, summation

p = [0.2, 0.3, 0.3, 0.1, 0.1]
l = symbols('l')
j = symbols('j')
eq= summation(j*q[j]/(l-j), (j, 0, 4))

s= solve(eq, l)

But this gives me an error for q[j] as j is a Symbol object here and not an integer. If I don't make j as symbol, I cannot evaluate the eq expression. Does anyone know how to do this?

Edit: p = 1-q in the above, hence q[j] should have been replaced by (1-p[j]).

Counterplot answered 31/10, 2020 at 20:25 Comment(0)
J
2

List p needs to be converted into symbolic array before it can be indexed with symbolic value j.

from sympy.solvers import solve
from sympy import symbols, summation, Array

p = Array([0.2, 0.3, 0.3, 0.1, 0.1])
l, j = symbols('l j')
eq = summation(j * (1 - p[j]) / (l - j), (j, 0, 4))

s = solve(eq - 1, l) # [1.13175762143963 + 9.29204634892077e-30*I, 2.23358705810004 - 1.36185313905566e-29*I, 3.4387382449005 + 3.71056356734273e-30*I, 11.5959170755598 + 6.15921474293073e-31*I]

(assuming your p stands for 1 - q)

Julenejulep answered 1/11, 2020 at 0:20 Comment(1)
This solved my problem! Thank you for helping me out.Counterplot

© 2022 - 2024 — McMap. All rights reserved.