HP Forums

Full Version: CAS programs, order of LOCAL variables?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Something strange is happening depending on the order of LOCAL declarations in CAS programs. For example,

#cas
TEST(k):=
BEGIN
LOCAL a:=1,j

FOR j FROM 2 to k DO
IF odd(j) THEN
a:=a+1/(2*j-1);
ELSE
a:=a-1/(2*j-1);
END;
END;
RETURN a;
END;
#end

is unstable, and returns different results for the same input, and j and a get written into the CAS Vars catalog.

However, changing the LOCAL declaration works, e.g.
...
LOCAL j,a:=1
...

runs OK.

So, if a variable has been declared and defined a value, should a subsequent variable not appear on the same LOCAL statement?

BTW, this doesn't seem to be a problem with LOCAL statements in Home programs.
The debugger may be of help here. You can watch the vars.
You are missing a semicolon in your code in the LOCAL line. Also, (and it's been a while) but at some point I had concluded that local vars needed their own separate line when declared when I was putting together a replacement program for the SVD command. Also, ensure that the variables don't already exist prior to running your program.
(12-10-2016 09:20 PM)DrD Wrote: [ -> ]The debugger may be of help here. You can watch the vars.

I think the debugger still does not work on cas-programs.

Posted by Helge Gabert - Today 12:13 AM Wrote:So, if a variable has been declared and defined a value, should a subsequent variable not appear on the same LOCAL statement?
Imo I read somewhere that local variables assigned to a value should be declared at the end of the local statement.

Arno
Thanks for the replies, I forgot to post the ";" at the end of the LOCAL lines - - they are in the program, though.

If local variables assigned to a value should be declared at the end of the LOCAL statement, OK, that would explain it - - it is just weird that this would be true for CAS programs only.

Separate LOCAL lines for each variable is probably the safest! It would be nice if CAS programs could be debugged with the built-in debugger - - maybe in the next release?
Also, the CAS knows the limit of the infinite sum of the above series

sum(j=1, infinity, ((-1)^(j+1))/(2*j-1)) - - pi/4 Smile

but it doesn't seem to know the limit of the related, alternating harmonic series

sum(j=1, infinity, ((-1)^(j+1))/j) - - ln(2) Sad

I wonder if the CAS employs a lookup table, or if it tries out various convergence criteria.
If you declare local variables and assign them, then priorities for assignation apply, and local a:=1,j is like local a:=(1,j). You must add parenthesis: local (a:=1),j; or enter 2 local statements or assign them after declaration.
For sums, there is no table lookup. The current version of Xcas returns ln(2) for sum( ((-1)^(j+1))/j,j,1,inf), therefore it should work in a future release on the Prime.
Thanks. I appreciate it.
Reference URL's