在传递给sum()之前强制评估索引表达式 [英] Force evaluate index expression before passing to sum()

查看:104
本文介绍了在传递给sum()之前强制评估索引表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个(以某种方式)增强的sum函数,该函数一次获取多个索引,但是我不明白如何使其工作.这是我目前拥有的:

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)

我认为可以通过在传递给sum函数之前强制Maxima将first(indexes)扩展为符号来解决此问题.我尝试了''(...)ev(..., nouns),但没有成功.

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.

推荐答案

在阅读并尝试后,我得出了以下解决方案,该解决方案使用apply函数预先评估sum的参数:

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:
不幸的是,上面的代码有问题,因为它仅适用于相对简单的表达式.在我的情况下,直接方法在nsum失败的地方可以很好地工作:

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:

该代码确实有效.意外地将它保留在rot2定义中,而不仅仅是k.

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

这篇关于在传递给sum()之前强制评估索引表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆