# Evaluate with a data set?

Can sage evaluate an expression with a given data set like ev function in maxima?

For example something like:

    A,B = var('A,B')
data = [A==1,B==2]
A + B with data
3
A + B
A + B


Thanks for help.

edit retag close merge delete

Sort by » oldest newest most voted

I think you are looking for the subs() method of symbolic expressions.

sage: var('A B')
(A, B)
sage: data = {A:1,B:2}
sage: expr = A+B
sage: expr
A + B
sage: expr.subs(data)
3


This will substitute as a dictionary. You can also do

sage: expr.subs(A=1,B=2)
3


if you like that syntax. Does that help?

more

@stanislav: As kcrisman does, note that it's more Pythonic to store key, value pairs in a dict than as a list of equations. That said, (a+b).subs_expr(*data) should work for lists of equations too.

Thanks, the second variant is the more comfortable for me, because then I can use a list of sets and put it into a for loop.

I think, the is no better way in sage because the way, you can use it in maxima can not be used in python. In maxima you can give the data list after an expression just by typing a comma like:

A+B,data


But I'm glad, the way with subs is working fine.

more

Great - especially feel free to use the *list unpacking syntax DSM mentions. (You can also accept the answer if you like it enough :-) )