【问题标题】:Maple Error: final value in for loop must be numeric or characterMaple 错误:for 循环中的最终值必须是数字或字符
【发布时间】:2021-08-28 17:44:58
【问题描述】:

我想在 Maple 中绘制这个简单的程序。

test:=proc(n)
    local i,t;  
    for i from 1 to n do
        t:=1;
    od;
    return t;
    end:

程序本身运行良好。

> test(19)
                               1

当我想绘图时,出现以下错误:

> plot(test(x),x=1..10)
Error, (in test) final value in for loop must be numeric or character

请帮忙

【问题讨论】:

    标签: maple


    【解决方案1】:

    Maple 通常的评估模型是,传递给命令的参数会在命令自身过程的主体内完成计算之前预先评估。

    因此,如果您将 test(x) 传递给 plot 命令,那么 Maple 将预先评估该参数 test(x)x 只是一个符号名称。

    只是在绘图构建的后期,plot 命令才会用实际数值替换该 x 名称。

    所以,参数test(x) 是预先评估的。但是,让我们看看当我们尝试对test(x) 进行这种预先评估时会发生什么。

    test:=proc(n)
      local i,t;  
      for i from 1 to n do
        t:=1;
      od;
      return t;
      end:
    
    test(x);
    Error, (in test) final value in for loop
    must be numeric or character
    

    我们可以看到,您的 test 过程未设置为接收非数字符号名称,例如 x 作为其自己的参数。

    换句话说,问题在于您传递给plot 命令的内容。

    这类问题有时被称为“过早评估”。这是一个常见的 Maple 使用错误。有几种方法可以避免这个问题。

    一种方法是利用plot 命令的所谓“运算符形式”调用序列。

    plot(test, 1..10);
    

    另一种方法是延迟对test(x) 的评估。下面使用所谓的未评估引号(也称为单右勾号,即撇号)会延迟对 test(x) 的评估。这会阻止 test(x) 被评估,直到内部绘图例程将符号名称 x 替换为实际数值。

    plot('test(x)', x=1..10);
    

    另一种技术是重写test,这样对它的任何调用都将返回未经计算的结果,除非它的参数是数字。

    test:=proc(n)
      local i,t;
      if not type(n,numeric) then
        return 'procname'(args);
      end if;
      for i from 1 to n do
        t:=1;
      od;
      return t;
    end:
    
    # no longer produces an error
    test(x);
    
            test(x)
    
    # the passed argument is numeric
    test(19);
    
               1
    
    plot(test(x), x=1..10);
    

    我不会在这里展示实际的图,因为您的示例只生成了常数 1(一)的图。

    【讨论】:

      猜你喜欢
      • 2019-10-15
      • 2022-07-14
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2015-09-22
      • 2018-04-24
      • 2013-10-02
      相关资源
      最近更新 更多