代码之家  ›  专栏  ›  技术社区  ›  Yaroslav Bulatov

Mathematica中求和的自动生成

  •  2
  • Yaroslav Bulatov  · 技术社区  · 14 年前

    这是我在执行 Generalized Distributive Law . 假设您需要自动生成以下表单的表达式

    http://yaroslavvb.com/upload/sum-prod-formula.png

    sumProduct(factors,fixedVariables,fixedValues,freeVariables,freeRanges)
    

    哪里

    factors={{1,4},{3,4},{3,4,5}}
    fixedVariables={1,3}
    fixedValues={-1,9}
    freeVariables={4,5}
    freeRanges={Range[5],Range[6]}
    

    该函数的输出将等于

    Total[{f14[-1,1]f34[9,1]f345[9,1,1],f14[-1,2]f34[9,2]f345[9,2,1],....}]
    

    f项的表示可能不同,即f[1,4,-1,1]而不是f14[-1,1]。使用整数引用每个变量也是一种设计选择。

    有人能建议一种优雅的方法来实现SumProduct吗?

    编辑11/11 Janus的解决方案,为可读性重写

    factors = {{1, 4}, {3, 4}, {3, 4, 5}};
    vars = {{1, {-1}}, {3, {9}}, {4, Range[5]}, {5, Range[6]}};
    
    (* list of numbers => list of vars *)
    arglist[factor_] := Subscript[x, #] & /@ factor;
    
    (* list of factors => list of functions for those factors *)
    terms = Apply[f[#], arglist[#]] & /@ factors;
    
    (* {var,range} pairs for each variable *)
    args = {Subscript[x, #1], #2} & @@@ vars;
    
    Sum[Times @@ terms, Sequence @@ args]
    
    1 回复  |  直到 14 年前
        1
  •  3
  •   Janus    14 年前

    variables={{1,{-1}},{3,{9}},{4,Range[5]},{5,Range[6]}};
    

    那么你的 sumProduct 可以非常简洁地实现

    sumProduct[f_, factors_, vars_] := Module[{x}, Sum[
       Times @@ ((Subscript[f, ##] @@ (Subscript[x, #] & /@ {##}) &) @@@ factors),
       Sequence @@ ({Subscript[x, #1], #2} & @@@ vars)]]
    

    它被称为 sumProduct[f,factors,variables] 吐出一个长的东西:

    Subscript[f, 1,4][-1,1] Subscript[f, 3,4][9,1] Subscript[f, 3,4,5][9,1,1]+....
    

    这就是你想要的吗?