On Jun 13, 2010, at 4:49 PM, Alan Bromborsky wrote:
> Aaron S. Meurer wrote:
>>> Now the question is if I then set diff_flg=True is there a way to
>>> recalculate z so that z = 2*x_1+x_1**2+x_2**2 is returned.
>>>
>>>
>>
>> That's what happens for me:
>>
>> In [58]: exec"""
>> from sympy import *
>> x_1 = Symbol('x_1')
>> x_2 = Symbol('x_2')
>> df = Function('df')
>> diff_flg = True def df_1(F):
>> global x_1,diff_flg
>> if diff_flg:
>> return(diff(F,x_1))
>> else:
>> return(df(F))
>> if __name__ == '__main__':
>> x = Symbol('x')
>> df = Function('df')
>> print df
>> y = x_1**2+x_2**2
>> print x,x_1,x_2,y
>> z = y + df_1(y)
>> print z
>> """
>> df
>> x x_1 x_2 x_1**2 + x_2**2
>> 2*x_1 + x_1**2 + x_2**2
>>
>> Are you saying you want it to happen automatically, without recalculating z?
>> In that case, you will need to make z itself a function. See
>> http://docs.sympy.org/gotchas.html#variables-assignment-does-not-create-a-relation-between-expressions.
>>
>> Aaron Meurer
>>
>>
> After setting diff_flg = True is there a way of explicitly telling z to
> recalculate using the new value of diff_flg (It does not have to
> happen automatically when the value of diff_flg is changed).
>
>
Yes. See the link above. If z is a variable, once something is bound to it,
it remains unchangeable (SymPy objects are immutable). The workaround, as
suggested on that page, is to have something like
def z():
return y + df_1(y)
Then use z() instead of z, and every time you use it, it will use the current
value of diff_flg. Of course, if you bind that to some other variable, you
will need to do the same thing for it too. If this ends up becoming too
complicated for what you are trying to do, you might consider restructuring how
you are calculating things, or else create some kind of mutable wrapper object
that handles recalculating things for you.
Aaron Meurer
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sympy?hl=en.