Summation and solve

42 views
Skip to first unread message

Julio Avila

unread,
Aug 17, 2014, 9:44:36 PM8/17/14
to sy...@googlegroups.com
Hi!
I try to solve loglik with sympy. Here an example:

from sympy import *

sigma2 = symbols('sigma2', real=True, positive=True)
alpha, beta =symbols('alpha beta', real=True)
k, n = symbols('k n', integer=True)
Xk = Indexed('X', k)
Yk = Indexed('Y', k)

loglik = -1/2 * log(2*pi*sigma2)  - 1/(2*sigma2) * Sum( (Yk - alpha - beta*Xk)**2, (k,1,n))

ldbeta = diff(loglik, beta)


Now I try to

>>>betahat = loglik.diff(beta).solve(beta)

Traceback (most recent call last):
  File "<pyshell#114>", line 1, in <module>
    loglik.diff(beta).solve(beta)
AttributeError: 'Mul' object has no attribute 'solve'


but don't work. Ideas?



Chris Smith

unread,
Aug 18, 2014, 12:40:42 AM8/18/14
to sy...@googlegroups.com

>>>betahat = loglik.diff(beta).solve(beta)



solve is a function, not a method. Sum doesn't (apparently) have a method to pull out terms that are independent of the summation symbol so you have to do that by hand: get beta on the outside of the Sum. Then solve for beta. The following is not robust, but exemplifies what I am talking about:

```
>>> id = lambda f,l,i: f.as_independent(l[0])[i]
>>> eq.replace(Sum,lambda f,l:id(f,l,0)*Sum(id(f,l,1), l))
-alpha*Sum(X[k], (k, 1, n))/sigma2 - beta*Sum(X[k]**2, (k, 1, n))/sigma2 + Sum(X
[k]*Y[k], (k, 1, n))/sigma2
>>> solve(_, beta)
[(-alpha*Sum(X[k], (k, 1, n)) + Sum(X[k]*Y[k], (k, 1, n)))/Sum(X[k]**2, (k, 1, n))]
```

solve (or some method) should be able to pull independent symbols out of the summation.
Reply all
Reply to author
Forward
0 new messages