Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maple Error: final value in for loop must be numeric or character

Tags:

maple

I have this simple procedure in Maple that I want to plot.

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

The procedure itself works fine.

> test(19)
                               1

When I want to plot I get the following Error:

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

Please help

like image 803
Rolf Avatar asked May 19 '26 06:05

Rolf


1 Answers

Maple's usual evaluation model is that arguments passed to commands are evaluated up front, prior to the computation done within the body of the command's own procedure.

So if you pass test(x) to the plot command then Maple will evaluate that argument test(x) up front, with x being simply a symbolic name.

It's only later in the construction of the plot that the plot command would substitute actual numeric values for that x name.

So, the argument test(x) is evaluated up front. But let's see what happens when we try such an up front evaluation of 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

We can see that your test procedure is not set up to receive a non-numeric, symbolic name such as x for its own argument.

In other words, the problem lies in what you are passing to the plot command.

This kind of problem is sometimes called "premature evaluation". It's a common Maple usage mistake. There are a few ways to avoid the problem.

One way is to utilize the so-called "operator form" calling sequence of the plot command.

plot(test, 1..10);

Another way is to delay the evaluation of test(x). The following use of so-called unevalution quotes (aka single right ticks, ie. apostrophes) delays the evaluation of test(x). That prevents test(x) from being evaluated until the internal plotting routines substitute the symbolic name x with actual numeric values.

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

Another technique is to rewrite test so that any call to it will return unevaluated unless its argument is numeric.

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);

I won't bother showing the actual plots here, as your example produces just the plot of the constant 1 (one).

like image 185
acer Avatar answered May 27 '26 06:05

acer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!