Force evaluate index expression before passing to sum()

南楼画角 提交于 2019-12-11 03:32:20

问题


I want to write an (somehow) enhanced sum function which takes a number of indices at once, but I cannot understand how to get it work. Here is what I currently have:

(%i1) nsum(indexes, expr) :=
          if indexes = []
          then expr
          else nsum(rest(indexes), sum(expr, first(indexes),1, N)) $

(%i2) nsum([i,j], i+j), nouns;
      sum: index must be a symbol; found intosym(first(indexes))
      #0: nsum(indexes=[k,j],expr=k+j)

I think this could be fixed by forcing Maxima expand first(indexes) into a symbol before passing to sum function. I tried ''(...) and ev(..., nouns), but without any success.


回答1:


After some reading and trying I came to the following solution which uses apply function to pre-evaluate arguments for sum:

nsum(indexes, expr) :=
    if indexes = []
    then expr
    else nsum(rest(indexes), apply(sum, ['expr, indexes[1], 1, N])) $

UPD1:
Unfortunately, there is something wrong with the above code, as it works well only for relatively simple expressions. In my case the straightforward approach works fine where nsum fails:

(%i1) rot[i](f) := sum(sum(sum(sum(
      G[r,i]*G[q,j]*w[i,j,k]*('diff(f[k], y[q]) + sum(K[k,q,m]*f[m], m, 1, N)),
        r, 1, N),
        j, 1, N),
        k, 1, N),
        q, 1, N) $

(%i2) rot2[i](f) := nsum( [r,j,k,q],
        G[r,i]*G[q,j]*w[i,j,k]*('diff(f['k], y[q]) + sum(K[k,q,m]*f[m], m, 1, N))) $

(%i3) rot[1](f);
(%o3) ... Yelds the result.

(%i4) rot2[1](f);
apply: subscript must be an integer; found: k
lambda([i,j],diff(ys[i],x[j]))(i=k,j=1)

UPD2:

The code works indeed. It was 'k accidentally left in rot2 definition instead of just k.



来源:https://stackoverflow.com/questions/31566284/force-evaluate-index-expression-before-passing-to-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!