How does one write this pseudocode as a maple program?

355 Views Asked by At

INPUT n, x1, x2, . . . , xn.

OUTPUT NORM.

Step 1 Set SUM = 0.

Step 2 For i = 1, 2, . . . , n set SUM = SUM + x^2(i).

Step 3 Set NORM = SUM1/2.

Step 4 OUTPUT (NORM);

STOP.

I am having a hard time translating pseudocode into real code using the Numerical Analysis Burden and Faires book.If someone can show me this easy example i will hopefully be able to move forward.

1

There are 1 best solutions below

0
On

There are many, many ways to do this. I'll assume that you are meant to pass the input values $x_{i}$ in some kind of data structure like a vector. Here is one way to do it. (Note that you do not need to pass the size $n$, as that is part of the data structure, gotten with the numelems command.)

mynorm := proc( x )
    local i;
    sqrt( add( x[ i ]^2, i = 1 .. numelems( x ) ) )
end proc:

You could use a list or Vector here:

> mynorm( [ 1, 2, 3, 4 ] );
                                   1/2
                                 30

> mynorm( Vector( [ 1, 2, 3, 4 ] ) );
                                   1/2
                                 30

> mynorm( Vector( [ 1, 2, 3, 4 ], datatype = float[8] ) );
                            5.47722557505166

A more direct translation of the pseudo-code is:

mynorm := proc( x )
    local i, sum;
    sum := 0;
    for i from 1 to numelems( x ) do
        sum := sum + x[ i ]^2
    end do;
    sqrt( sum )
end proc:

However, the first version I gave above is more idiomatic.

You can embellish these with argument type-checking, special handling for numerics, etc., but this should give you the basic idea. For help with Maple programming, you might check out MaplePrimes at http://www.mapleprimes.com.

(I assume the point is to learn Maple. If you just want to compute a vector norm, you would be better off using builtin tools that are careful to avoid overflow, and will be much faster, etc.)