Reputation: 41
I am trying to pass image1 in my code when i copy and paste this as text it looks like this ∑(i=1,n)(a+m*x*(i)-y*(i))^2
.
but it does not work.
following is my code which is working with a different syntax:
from sympy import symbols,sympify,solve,Eq,Symbol
from sympy import symbols,Eq,sympify,summation
expr = **('summation((m * x*(i) + a - y*(i))^2, (i, 0, n))')**
Eq1 = Eq(sympify(expr))
print(Eq1)
values = {2001,10,2,3,5}
arr_symbols = list(Eq1.free_symbols)
print(arr_symbols)
Method1(arr_symbols,values,expr)
def Method1(arr_symbols,Values,expr):
from sympy import symbols, Eq, solve, pprint, integrate, sympify
z = symbols('z')
Formula = Eq(sympify(expr),z)
print(Formula)
index = 0
for i in Values:
Formula = Formula.subs(arr_symbols[index],i)
index+=1
print(solve(Formula))
but what i want to do is to use ∑(i=1,n)(a+m*x*(i)-y*(i))^2
and ask sympy to convert it for me.
Upvotes: 4
Views: 1079
Reputation: 91450
SymPy can represent this equation, but it can only parse Python. You might be able to write extensions to its parser to handle this sort of thing (see https://docs.sympy.org/latest/modules/parsing.html). It should be possible in principle, although it might not be straightforward. I would only recommend doing this the syntax of your expressions is already very close to Python. If it isn't (and it looks like it isn't), it would be better to a real parsing library like ANTLR to build up a grammar for your expressions. You can then use that to parse into SymPy (see for example how the sympy.parsing.latex
module is written).
I don't know if there is pre-existing library in Python that handles your types of expressions. I'm not aware of any. At best you might be able to find a grammar that someone has already written, so you don't have to write it yourself.
Upvotes: 1
Reputation: 18939
If you are, given a
, m
and values for x
and y
and are trying to compute the sum of the squares of the residuals, then it would be better to write a function that does that or do something like this:
>>> x = [1, 2, 3]
>>> y = [4, 7, 11]
>>> a = 2
>>> m = 5
>>> sum((a + m*xi - yi)**2 for xi, yi in zip(x, y))
70
Upvotes: 0