The problem is that codegen doesn't support generating Sum yet. It's something we want to add, but it's harder because a summation requires generating code for a loop.
Since you know the bounds of the summation ahead of time, you can evaluate it to a normal addition using doit() (the expression for the derivative can also be simplified. I would suggest d_func.expand().doit()). Aaron Meurer On Tue, Dec 6, 2022 at 5:28 AM ajp <[email protected]> wrote: > > Hi, > > Very new to Sympy. Hoping to generate a Sum of an indexed expression, then > form a simple expression, and then take derivatives. Finally, I'd like to > output the solution using codegen. I'm really struggling. I suspect my use of > Sum and or indexed expressions is wrong. All help really appreciated: > > import sympy as sm > > # would prefer to use the first one of these > #Ns = sm.symbols('Ns', cls=sm.Idx) # gives IndexError: tuple index out of > range > Ns = 10 # gives FIXME: No specialized handling of type <class > 'sympy.concrete.summations.Sum'> > > sp = sm.Idx('sp', Ns) > S = sm.IndexedBase('S')[sp] > total = sm.Sum(S, sp) > > # construct simple expression > func = sm.log(S/total) > print(func) > > # derivative of Sum > d_total = total.diff(S) > print(d_total) > > # derivative of expression > d_func = func.diff(S) > print(d_func) > > # print > from sympy.utilities.codegen import codegen > codegen( [("func", func), ("dfunc", d_func)], language="C", prefix="test", > to_files=True, header=False, empty=False) > > -- > You received this message because you are subscribed to the Google Groups > "sympy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to [email protected]. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sympy/3c9728f8-e406-410f-afb0-b72974f7c6e2n%40googlegroups.com. -- You received this message because you are subscribed to the Google Groups "sympy" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/CAKgW%3D6LbCXsfoTOTuVDM6g1sk%2B%3D__cLfcL%3DRe%3DJLdUrEig14AQ%40mail.gmail.com.
