acer

32313 Reputation

29 Badges

19 years, 312 days
Ontario, Canada

Social Networks and Content at Maplesoft.com

MaplePrimes Activity


These are answers submitted by acer

The parsing of strings will produce global names such as :-Sample. So your example acts like this,

> use Statistics in :-Sample(:-RandomVariable(Normal(0, 1)),100)  end use;
                   Sample(RandomVariable(Normal(0, 1)), 100)

The names in that output are the untouched global (:- prefixed) names.

All I can think of right now, to make this work for you, is substitution.

> whole:=[seq(x=Statistics[x],
>             x in map(convert,[exports(Statistics)],`global`))]:

> use Statistics in
>   eval(parse("Sample(RandomVariable(Normal(0, 1)),100)",statement),whole);
> end use;
                          [ 100 Element Row Vector ]
                          [ Data Type: float[8]    ]
                          [ Storage: rectangular   ]
                          [ Order: Fortran_order   ]

> use Statistics in
>   eval(:-Sample(:-RandomVariable(Normal(0, 1)),100),whole);
> end use;
                          [ 100 Element Row Vector ]
                          [ Data Type: float[8]    ]
                          [ Storage: rectangular   ]
                          [ Order: Fortran_order   ]

This is one of the very few times that I've wanted the [] rather than the :- notation for referencing module exports, so as to be able to generate that substitution sequence programatically.

acer

I'm not sure that I quite follow. If you have assigned something to name expr then entering simply expr; at the top-level, or print(expr); inside a procedure, should display its current value.

This brings up a related notion. People often talk about assigning to lots of variables. (It's a FAQ here, how to make assignments from the sequence of results returned by solve. The best answer is probably "Why do you want to do that?") A great deal of the time it is easier to instead use 2-argument eval, eg, eval(expr,[solve_answer]). Assigning to a whole bunch of variables is often just unnecessary. It brings the difficulty that, once x say has a value, it can't be used to form a new general expression unless its first unassigned.

And this is all aside from the general under-use of procedures in people's code, which deserves a blog in its own right.

acer

One should supply either a list or a Vector according to which particular form is used.

> NonlinearFit((x,y,a,b,c)->exp(a+b*x+c*y), XY, Z,
>              initialvalues=initxy);

                            [-0.209656805295074966]
                            [                     ]
                            [0.413711756831582622 ]
                            [                     ]
                            [0.0552760189352312359]

> NonlinearFit(exp(a+b*x+c*y), XY, Z,
>              [x,y],initialvalues=[a=1,b=2,c=3]);
 exp(-0.209656805295074966 + 0.413711756831582622 x + 0.0552760189352312359 y)

In your attempt, you use an expression with names a,b,c and a 3-Vector. But you could have used tt,rr,ss as the names. How then would NonlinearFit know which name to associate with which entry of the 3-Vector? There's no really great way to infer the (intended) order of the names, so as to be able to associate them with the Vector. But in the case of an operator (procedure) rather than an expression, the unnamed entries of the Vector can be naturally matched with the procedural parameters of the operator.

 acer

One problem is that, in Maple 11.02, there is no member Size in the ArrayTools package. Something like this might serve as an alternate (for Array input) to the simple way that you are calling it,

> Size := proc(M::Array,n::posint)
> local rng;
>   rng := ArrayDims(M)[n];
>   abs(op(2,rng)-op(1,rng))+1;
> end proc:
>
> A := Array(0..1,-4..3,1..6,-17..-15):
> Size(A,1),Size(A,2),Size(A,3),Size(A,4);
                                  2, 8, 6, 3

Another issue is that you omitted the uses statement in your procedure. Alec's proc had this line, which allowed Determinant and the Typeset calls to resolve to the exports of their respective packages,

uses ArrayTools, LinearAlgebra, Typesetting;

acer

CrossProduct is not a "top-level" command. There are a few routines with that name, inside packages. See the using packages help-page.

My guess is that you have omitted the step that loads the appropriate package, and so the apparent call to a CrossProduct routine returns just the unevaluated function call. Try issuing this first,

with(VectorCalculus):

or,

with(LinearAlgebra):

depending on which was in use in that part of the textbook.

acer

Why is the result of residuals(N1, N2, lambda1, lambda2) being wrapped in a list? Try not enclosing it in [] square brackets before passing to NLPSolve, or pass op() of it as the objective.

acer

It is not possible to have the entries get printed as m[i,j] with the same m as the variable to which the Matrix is assigned. In a related way, m[i,j] cannot be referenced for symbolic (unassigned, nonnumeric) i and j.

It is possible to use another symbol, however.

> m := Matrix(2,3,symbol=M);
                          [M[1, 1]    M[1, 2]    M[1, 3]]
                     m := [                             ]
                          [M[2, 1]    M[2, 2]    M[2, 3]]

> m[i,j];
Error, bad index into Matrix

There may be ways to use escaped local name m, or m rebound to a module export. But it's probably more effort than it's worth (and the created Matrix objects almost certainly couldn't get saved to .m or .mla and accessed in new sessions without encountering an infinite recursion. (I've tried..)

The now deprecated lowercase matrix has the property you describe, by default. That's a consequence of matrices having last_name_eval (which is a source of both good and evil).

> m := matrix(2,3):
> evalm(m);
                        [m[1, 1]    m[1, 2]    m[1, 3]]
                        [                             ]
                        [m[2, 1]    m[2, 2]    m[2, 3]]
 
> m[i,j];
                                    m[i, j]

acer

> a := Matrix(3,3,shape=symmetric):

> a[1,2]:=17:
> a[2,1];
                                      17

acer

This can be done quite easily with strings, by searching for longest substrings. The routine cat can be used to concatenate list entries into a string.

> F:=proc(x,b::posint,N::posint)
> local y,p:
>  if b>16 then error; end if;
>  y:=subs([10=A,11=B,12=C,13=D,14=E,15=F],
>          ListTools:-Reverse(
>    convert(floor(evalf[floor(N*ln(b)/ln(10))](x*b^N)),base,b))):
>  p:=nops(y)-N;
>  cat(op(y[1..p]),".",op(y[p+1..N]));
> end proc:
>
> S1 := F(sqrt(8),12,4500):
> S2 := F(sqrt(19),12,4500):

> StringTools:-LongestCommonSubString(S1,S2);
                                  "470B14568"

acer

Someone might post a more direct way, for your second example of SphericalY(1,1,phi,theta).

> expr := SphericalY(1,1,phi,theta):
> simplify(expand(combine(convert(expr,elementary)))) assuming phi::real;

                             1/2
                     -1/4 I 6    exp(theta I) | sin(phi) |
                     -------------------------------------
                                       1/2
                                     Pi

note: LegendreP does not automatically convert to elementary functions (as you seem to have suggested), although simplify can do that to it.

acer

While LinearAlgebra:-Equal (or the undocumented built-in, EqualEntries) are quite convenient for exact or symbolic Matrices, verify can also be used.

Careful comparison of floating-point Matrices or Vectors can be done using verify,Matrix along with verify,float. For example,

> M:=Matrix( 2, 2, [[0.3222, 0.5001], [1.0320, 0.9111]] ):
> S:=Matrix( 2, 2, [[0.3223, 0.5000], [1.03205, 0.911105]] ):

> verify( M, S, 'Matrix' );
                                     false
 
>  verify( M, S, 'Matrix(float(10^6))' );
                                     true
 
>  verify( M, S, 'Matrix(float(1,digits=5,test=2))' );
                                     false
 
>  verify( M, S, 'Matrix(float(10,digits=5,test=2))' );
                                     true

That last one tests that an absolute (test=2) entrywise comparison between M and S at 5 digits will have at most a difference of 10 units in last position (ulps). Which is true, since 0.50000 and 0.50010 vary by 10 ulps in an absolute comparison.

ps. People who write code often have their own distinctive style ("fist"). The variable name 'ee' is favoured by someone.

acer

You could also solve the characteristic polynomial of dFxdU, without having to convert to rationals.

solve(charpoly(dFxdU,lambda),lambda);
                                    (1/2)       /                      (1/2)\
                  rho u + (rho g pt)         1. \-1. rho u + (rho g pt)     /
u, u, u, u, u, u, -----------------------, - --------------------------------
                            rho                            rho               

BTW, you might wish to also consider using the more modern LinearAlgebra, VectorCalculus, and Matrix rather than linalg and array. It doesn't make things easier for your mixed symbolic+float dFxdU, but some aspects can be easier such as no need for evalm and no last_name_eval.

acer

An important difference is that you introduced floating-point values into dFxdU (eg, 0.5 rather than 1/2).

If I replace those three instances of 0.5 in the creation of dFxdU by the exact quanity 1/2 then I get these results,

> eigenvalues(dFxdU);
                      (1/2)                       (1/2)                  
    rho u + (rho g pt)         -rho u + (rho g pt)                       
    -----------------------, - ------------------------, u, u, u, u, u, u
              rho                        rho                             

If your matrix, with a mix of floats and multiple variables, has already been created then you can convert the floats to rationals like this,

> map(convert, dFxdU, rational);

ps. There are quite a few corners of Maple which have difficulty with the mix of multivariable expressions containing floating-point numbers. On the one hand, there are actually some poorly understood areas for such input. But there are also some tasks for which straightforward approaches can lead to decent answers (ie. for some such low order eigensystems, by computing the nullspace of the characteristic Matrix with lambda replaced by each explicit eigenvalue). There are parts of Maple where a practical approach is missing on the grounds that the general case is not possible or completely understood.

acer

It seems that your procedure p produces some nonnumeric results under evalhf (which is the numeric interpreter that plot uses by default).

> evalhf(p(0.02));
                              Float(undefined)

Try this, as a workaround,

plot(t -> evalf[Digits](p(t)), 0.0 .. 0.1);

acer

One way to look at it:
> rsolve(Q(k,x)=Q(k-1,x)+1,Q(n,x));
                                  Q(0, x) + n
 
> eval(%, Q(0,x)=x);
                                     x + n

acer

First 297 298 299 300 301 302 303 Last Page 299 of 336