# HP Forums

Full Version: Programming examples
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

Newton's Method implemented several ways. Videos of the programming:

Click the video description for parts 2 and 3. Source code below.

Style 1: Expect user to enter function into F1 in the function app, and guess and tolerance are hardcoded.

Style 2: Provide a graphical interface for user input; automatically creates UI when run from program catalogue

Style 3: Bypass graphical interface; create a function instead

Style 4: Expect f(x) in F1 but still have function interface for Newton's Method (to get around a small issue with running from program catalogue)

Style 1: Initial attempt as a solution to a specific problem

```export NEWT()
begin
local n,xold,xnew,err;
err:=.000001;
n:=0;
xnew:=2;
xold:=xnew-2*err;
F0:=expr("'X-F1(X)/(" + diff(F1(X),X) + ")'");
L1:={};
while (abs(xnew-xold)>err and n<100) do
n:=n+1;
L1(n):=xnew;
xold:=xnew;
xnew:=F0(xold);
end;
L1(n+1):=xnew;
end;```

Syle 2: Creating a user interface

```export NEWT2()
begin
local n,xold,xnew,err,N,f;
N:=100; err:=.00001; xnew:=1;
if input(
{f,xnew,err,N},
"Newton's Method",
{"f(X)=", "Guess=", "Error=", "Max Iter.="},
{
"Enter the function surrounded by single quotes",
"Enter the initial guess",
"Enter the tolerance",
"Enter the maximum number of iterations"
},
{f,xnew,err,N}
) then
F1:=f;
CAS("F0:=id-F1/F1'");
L1:={}; L1(1):=xnew;
for n from 2 to N+1 do
xold:=xnew;
xnew:=F0(xold);
L1(n):=xnew;
if abs(xnew-xold)<err then break; end;
end;
editlist(L1);
end;
end;```

Style 3: Function-like command

```export NEWT3(f,guess,tol,maxiter)
begin
local n,xold,xnew,err,N;
N:=maxiter;
err:=tol;
xnew:=guess;

F1:=f;
CAS("F0:=id-F1/F1'");
L1:={}; L1(1):=xnew;
for n from 2 to N+1 do
xold:=xnew;
xnew:=F0(xold);
L1(n):=xnew;
if abs(xnew-xold)<err then break; end;
end;
editlist(L1);

end;```

Style 4: Mix of Style 1 and 3

```export NEWT3(guess,tol,maxiter)
begin
local n,xold,xnew,err,N;
N:=maxiter;
err:=tol;
xnew:=guess;

//    F1:=f;
CAS("F0:=id-F1/F1'");
L1:={}; L1(1):=xnew;
for n from 2 to N+1 do
xold:=xnew;
xnew:=F0(xold);
L1(n):=xnew;
if abs(xnew-xold)<err then break; end;
end;
editlist(L1);

end;```

Thanks Han!

Very nice and thanks!

Thank you for these explanations Han,

But manipulations of symbolic expressions within a program still very confusing to me.

Sometime you don't use CAS() cmd :

```F0:=expr(" 'X-F1(X)/(" + diff(F1(X),X) + ")' ");
```

Sometime you must use CAS()...

I really need to clarify things. In a program what is the best way to capture a symbolic expression from the INPUT command ?

How to store results of symbolics manipulations in a locals variables ?

Use the SUBST command inside of a program, for example...

I wish I could just write something like this :

```EXPORT test()
LOCAL f,g,h,u;
BEGIN
INPUT(f); // assuming f of 'x'
g:=diff(f,x); // or CAS(g:=diff(f,x));
h:=f('i*x)'); // or CAS(h:=SUBST(f,'x','i*x'));
u:=invlaplace(f);
F1:=f('X');
F2:=g('X');
F3:=h('X');
F4:=u('X');
END;
```

Have a nice day !

Quote:
Sometime you don't use CAS() cmd :

```F0:=expr(" 'X-F1(X)/(" + diff(F1(X),X) + ")' ");
```

Sometime you must use CAS()...

I really need to clarify things. In a program what is the best way to capture a symbolic expression from the INPUT command ?

How to store results of symbolics manipulations in a locals variables ?

Firstly, all symbolic objects must start and end with: '

EXPR() simply takes a string and tries to parse into something the calculator recognizes. It does all calculations in Home view. Fortunately, symbolic objects are recognized by the single quotes.

So EXPR("'X-2*X'") would just be the symbolic X-2*X whereas EXPR("X-2*X") would actually compute the value of X-2*X using the current value of X. -- Note the ' in the first case and the lack of ' in the latter case.

If you want to do symbolic manipulation in the sense of integration, laplace transforms, derivatives, etc. then it must be done in CAS.

Examples:

CAS(int('x-2','x'));

CAS(int('X^2-5*X','X'));

That said, some CAS commands _do_ work in Home View (such as subst() and diff().

If the only goal is to construct a symbolic object, and it can be done with strings, then use string objects whose first and last characters are ' and then convert from string into expressions with EXPR().

Example:

fsquare:=expr("'(" + string(f) + ")^2'");

In the example above, fsquare is a symbolic object. It is NOT a function.

EXPR() takes a string and tries to parse the string. CAS() is almost the same, but it parses it according to the CAS view rules.

CAS() basically does all the "stuff" inside the () as if you are in CAS view. However, there is a slight difference how CAS() works. If the argument of CAS() is a single string, then CAS() will actually execute the string as if it were typed in the command line.

For example,

CAS("x:=5+2/3") will cause the CAS to store 17/3 into the variable 'x'

CAS("f:=2*X-5") will cause the CAS to stored the formula 2*X-5 into f -- however because X is a global variable, it actually stores 2*0-5 or just -5 into f. So if you want to use global variables, you must enclose the "formula" in single quotes. That is, CAS("f:='2*X-5'") would be required. The same is true if you use CAS("f:=2*x-5") and x is defined as a number. Unlike X, x can be purged. So we can be lazy and type CAS("f:=2*x-5") and still get 2*x-5 (and not an evaluation of 2*x-5) as long as x is purged.

CAS("subst(2x-5,x,'i*X')") will return 2(i*X)-5

However,

CAS("x:=5+" + "2/3") will simply do string addition in the CAS environment.

So if X:=0 and f:='X^2-5' then something like F1:=CAS("subst(" + f + ",X,i*X)") would actually return just the string "subst(-5,X,i*X)" because f is evaluated to -5, which is then converted to a string, and then the strings "subst(", "-5", and ",X,i*X)" are added together, and finally (because we are storing into F1), this string is converted into a symbolic.

The issue here is that we have local variables which we want to use in the CAS environment. Unfortunately, CAS view DOES NOT recongize local variables! We cannot do anything like:

CAS("subst(" + f + ",X,i*X)")

because this just does string addition inside the CAS view.

In the home view, you can type:

CAS(subst('X^2-5','X','i*X')) and it would give the same result as typing in CAS view without using CAS(). Unfortunately, something like CAS(subst(f,'X','i*X')) would not work because f is a local variable inside a non-CAS program. So f would be evaluated according to non-CAS rules before being passed to subst().

This is where we can use CAS.function() and expr() together.

myexpression:=CAS.subst( expr("'" + string(f) + "'"), 'X', 'i*X'))

Note the addition of the single quotes (because the string command does not add them automatically for us).

I was able to get away with EXPR("'X-F(X)/(" + diff(F1(X),X) + ")'"); because diff() happens to behave nicely in home view when used with F1. F1(X) is treated as a symbolic object so I do not need to do any crazy type conversions.

Edited: 22 Oct 2013, 4:57 p.m.

Thank you very much Han. With you things become more clear in my mind. I began to write small applets that work well. And communicating with each other. Bode plot applet, Black plot applet temporal response applet ... I set the transfer function in any with "INPUT" form and I can switch to another by the "view" custom command menu.

I'm starting to find this machine very interesting !

Once you get used to the nuances, then it really is a fun machine to play with. But the initial growing pains are annoying :-)

Thanks Han!

Hi Han
Thanks for the examples. Please could you explain the use of "id" in your statement involving the line starting with Cas
Thanks John

Quote:
Hi Han
Thanks for the examples. Please could you explain the use of "id" in your statement involving the line starting with Cas
Thanks John

The CAS is able to handle functional algebra without having to specify the input variable of the functions involved. You see this often as: f(x) + g(x) but written simply as f + g.

So just as F0 and F1 are functions, "id" is the "identity" function. And F1' is also a function (namely the derivative of F1). So in words,

F0 := id - F1/F1'

means

F0 is defined to be the identity function minus the quotient of the function F1 and its derivative F1'

Any function in CAS can be used in a similar manner. For example, the squaring function may be typed as sq(x). So you can create a new function h that behaves like sq(x) -- except instead of typing:

h(x):=sq(x)

where we have to explicitly name the input variable, we can instead type:

h := sq

and then h(pi) would return pi^2. If you are wondering what the name of the input variable would be in these cases, the default appears to be _x. So

h := sq

is equivalent to

h(_x) := sq(_x)

Now, specifically for F0-F9, the input variable is X. The system changes the input variable automatically (it's just a dummy placeholder anyway) for us.

I hope that helps!

Edited: 24 Oct 2013, 2:25 p.m.

Hi Han
Thanks for the explanation,I understand perfectly.
Regards
John