如何在GAMS中递归定义参数?

发布于 2024-12-06 18:18:46 字数 926 浏览 1 评论 0原文

我需要定义一组具有自然递归关系的参数。

这是一个 MWE,我尝试在一组(九个)参数 S 上定义阶乘函数:

$title TitleOfProblem

set S / s1*s9 /;

alias(S, S1, S2);

set delta1(S1,S2);
delta1(S1,S2) = yes$(ord(S1) + 1 = ord(S2));

parameter f(S);

f(S) = 1$(ord(S) = 1) + (ord(S) * sum(S1$(delta1(S1, S)), f(S1)))$(ord(S) > 1);

display f;

“delta1”是一个关系,包含按排序顺序相差 1 的元素对。从逻辑上讲,f 的定义与阶乘函数(对于输入 1 到 9),但 GAMS 似乎不喜欢 f 是递归定义的。 GAMS 编译的输出看起来像这样:

f(S) = 1$(ord(S) = 1) + (ord(S) * sum(S1$(delta1(S1, S)), f(S1)))$(ord(S) > 1);
                                                          $141

141  Symbol neither initialized nor assigned
    A wild shot: You may have spurious commas in the explanatory
    text of a declaration. Check symbol reference list.

Question:

Is it possible to recursively Define aparameter in GAMS?如果没有,解决方法是什么?

(PS 有足够代表的人应该创建一个标签“GAMS”并将其添加到此问题中。)

I need to define a set of parameters that have a natural recursive relation.

Here is a MWE where I try to define the factorial function over a set of (nine) parameters S:

$title TitleOfProblem

set S / s1*s9 /;

alias(S, S1, S2);

set delta1(S1,S2);
delta1(S1,S2) = yes$(ord(S1) + 1 = ord(S2));

parameter f(S);

f(S) = 1$(ord(S) = 1) + (ord(S) * sum(S1$(delta1(S1, S)), f(S1)))$(ord(S) > 1);

display f;

"delta1" is a relation containing pairs of elements in sorted order that differ by 1. Logically, the definition of f matches the definition of the factorial function (for inputs 1 to 9), but GAMS doesn't seem to like that f is defined recursively. The output of GAMS compilation looks something like this:

f(S) = 1$(ord(S) = 1) + (ord(S) * sum(S1$(delta1(S1, S)), f(S1)))$(ord(S) > 1);
                                                          $141

141  Symbol neither initialized nor assigned
    A wild shot: You may have spurious commas in the explanatory
    text of a declaration. Check symbol reference list.

Question:

Is it possible to recursively define a parameter in GAMS? If not, what is a work-around?

(P.S. Someone with enough rep should create a tag "GAMS" and add it to this question.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

波浪屿的海角声 2024-12-13 18:18:46

有人向我展示了使用 while 循环的示例解决方案。然而,该解决方案特定于阶乘,不能推广到任意递归函数。

$title factorial

set S / s1*s9 /;

parameter f(S);
parameter temp;

Loop(S,
  temp=ord(s);
  f(S)=ord(s);
    While(temp > 1,
      f(S) = f(S) * (temp-1);
      temp = temp - 1;
    );
);

display f;

Someone showed me a solution for my example using a while loop. However, this solution is specific to factorial and does not generalize to an arbitrary recursive function.

$title factorial

set S / s1*s9 /;

parameter f(S);
parameter temp;

Loop(S,
  temp=ord(s);
  f(S)=ord(s);
    While(temp > 1,
      f(S) = f(S) * (temp-1);
      temp = temp - 1;
    );
);

display f;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文