acer

32510 Reputation

29 Badges

20 years, 12 days
Ontario, Canada

Social Networks and Content at Maplesoft.com

MaplePrimes Activity


These are answers submitted by acer

f := int(cosh(a*x)*cos(b*x), x):

simplify( convert( f, trigh) );


                 cosh(a x) sin(b x) b + sinh(a x) a cos(b x)
                 -------------------------------------------
                                    2    2                  
                                   a  + b                   

acer

This is about 33 times faster on my 64bit Linux system. How fast do you need it?

I expect that it could be made at least 10-20 times faster again, if the iterated action were burned into a evalhf'able or Compilable procedure that acted inplace on an Array of `n` values. And that could be split with Threads:-Task.

It seems to work for the example parameter values you gave. I would rather know that the approach works for other parameter values in which you are interested, before going to town on further optimization.

I put your original procedure at the end.

restart:

expr:=tan(theta_n) - C_a*Z_0*(-v^2*(Pi*n-theta_n)^2/x_l^2
             +omega_a^2)*x_l/(v*(Pi*n-theta_n)):

Equate([omega_a,v,x_l,C_a,Z_0],[100e9, 1e8, 0.3, 20e-14, 50.0]):
ee:=simplify(eval(expr,%));

                                                         2              
                          0.003333333333 (Pi n - theta_n)  - 300.0000000
     ee := tan(theta_n) + ----------------------------------------------
                                          Pi n - theta_n                

# We hope that this provides a contraction mapping which
# converges quickly:
ff:=simplify(map(arctan,op(1,ee)=-op(2..-1,ee)))
      assuming theta_n>-Pi/2, theta_n<Pi/2;

                          /                               2              \
                          |0.003333333333 (Pi n - theta_n)  - 300.0000000|
   ff := theta_n = -arctan|----------------------------------------------|
                          \                Pi n - theta_n                /

F:=N->unapply(eval(evalf(rhs(ff)),n=N),theta_n,proc_options=[hfloat]):

# Applying F to n produces a procedure, which we can
# iterate at initial values of theta_n.
F(117);

          proc(theta_n)                                           
          option hfloat;                                          
                                                                  
            -1.*arctan((0.003333333333*(%1)^2 - 300.0000000)/(%1))
          end proc;                                               
                                                                  
                                                                  
          %1 := 367.5663405 - 1.*theta_n                          

# For most all initial theta_n, F(117) converges in a
# small number of iterations. It might be that 10 iterations
# is enough, in general.
seq( (F(117)@@i)(11.0), i=0..10 );

     11.0, -0.334174918606374, -0.389865087453356, -0.390129467304736,

       -0.390130722191024, -0.390130728147372, -0.390130728175643,

       -0.390130728175778, -0.390130728175778, -0.390130728175778,

       -0.390130728175778

# Let's see whether many initial guesses converge to the same value
# after 10 iterations.
plot( (F(117)@@10), 0.1..11.0 );

# Let's always use 1.0 as the initial theta_n guess, and produce a
# plot for various values of n.
forget(evalf):
CodeTools:-Usage( plot( '(F(n)@@10)(1.0)', n=1..1000) );

memory used=6.09MiB, alloc change=0 bytes, cpu time=151.00ms, real time=146.00ms, gc time=0ns

restart:
# Now lets put it into a procedure.

new_get_theta_n_array:=proc(max_n::integer, omega_a::float, v::float,
                            x_l::float, C_a::float, Z_0::float)

    local ff, F, theta_n_array;
    ff:=simplify(expand(arctan(C_a*Z_0*(-v^2*(Pi*n-theta_n)^2
                                /x_l^2+omega_a^2)*x_l/(v*(Pi*n-theta_n)))));
    F:=N->unapply(eval(evalf(ff),n=N),'theta_n',proc_options=[hfloat]);
    # Here we always start iterating from guess theta_n=1.0, but
    # it might be even faster to start iterating from the previous
    # n's final iterate. If we keep it as is, though, we could Thread:-Task
    # this action and split across all the values of n to be computed.
    # Also, if convergence were ever slow then we could consider making
    # the number of iterations ba according to some additional proc argument
    # rather than fixed at 10 iterations.
    theta_n_array:=Array([seq( '(F(n)@@10)(1.0)', n=1..1000 )],datatype=float[8]);
    if ArrayNumElems(theta_n_array) <> max_n then

        printf("Bad Array Dimensions! Got too many or not enough solutions.");

        theta_n_array:="CHECK: get_theta_n_array()":

    end if;

    theta_n_array;

end:

CodeTools:-Usage( new_get_theta_n_array(1000,100e9,1e8,0.3,20e-14,50.0) ):

memory used=9.21MiB, alloc change=32.00MiB, cpu time=151.00ms, real time=158.00ms, gc time=20.00ms

plots:-listplot(%);

restart:

get_theta_n_array:=proc(max_n::integer, omega_a::float, v::float,
                        x_l::float, C_a::float, Z_0::float)

    local theta_n_array:=Array(

        select(x->Re(x)<evalf(Pi/2) and Re(x)>=-evalf(Pi/2),
               [seq(

        #NOTE: careful with fsolve - in some cases returns
        #      unevaluated equation

                    fsolve(tan(theta_n) - C_a*Z_0*(-v^2*(Pi*n-theta_n)^2
                             /x_l^2+omega_a^2)*x_l/(v*(Pi*n-theta_n)),
                           theta_n) , n=1..max_n)]

               , real)

                               , datatype=float[8]);

    if ArrayNumElems(theta_n_array) <> max_n then

        printf("Bad Array Dimensions! Got too many or not enough solutions.");

        theta_n_array:="CHECK: get_theta_n_array()":

    end if;

    theta_n_array;

end:

ans:=CodeTools:-Usage( get_theta_n_array(1000,100e9,1e8,0.3,20e-14,50.0) ):

memory used=308.13MiB, alloc change=117.85MiB, cpu time=5.28s, real time=5.28s, gc time=130.00ms

plots:-listplot(ans);

 


Download itsme0.mw

acer

Ok, so part of the instruction for this question is that you use the LinearAlgebra:-LeastSquares command. (Perhaps your instructor wants you to know how to set up such problems by hand...)

restart:

r:=Vector[row]([1,cos(x),sin(x),cos(2*x),sin(2*x)]);

                r := [1, cos(x), sin(x), cos(2 x), sin(2 x)]

varvec:=Vector([a,b,c,d,e]);

                                          [a]
                                          [ ]
                                          [b]
                                          [ ]
                                varvec := [c]
                                          [ ]
                                          [d]
                                          [ ]
                                          [e]

# Here is the formula we wish to use to approximate y(x).
# Notice that it has 5 unknown parameters. I'll refer to those a the 5 unknowns, below.

r . varvec;

              a + cos(x) b + sin(x) c + cos(2 x) d + sin(2 x) e

# Here are the given x and y data values.
# Notice that there are 9 data pairs.

xdata:=Vector([1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0]):
ydata:=Vector([2.33,0.0626,-2.16,-2.45,-0.357,2.21,2.75,0.636,-2.45]):

# If we plug a particular xdata value into the formula, and set that equal
# to the corresponding ydata value, then we have an equation that is linear
# in the 5 unknowns.

eval( r, x=xdata[1] ) . varvec = ydata[1];

       a + 0.5403023059 b + 0.8414709848 c - 0.4161468365 d + 0.9092974268 e = 2.33

# We could do the same thing for all 9 data pairs. That would give us 9
# equations that are linear in the 5 unknowns. That would be an overdetermined
# linear system, which could also be expressed in Matrix-Vector form and be solved
# using the LeastSquares command.

#
# First, here is the left-hand side of system    M . varvec = ydata
#

M := Matrix(9,5, (i,j)-> eval(r[j], x=xdata[i]) );

         [1   0.5403023059   0.8414709848  -0.4161468365   0.9092974268]
         [                                                             ]
         [1  -0.4161468365   0.9092974268  -0.6536436209  -0.7568024953]
         [                                                             ]
         [1  -0.9899924966   0.1411200081   0.9601702867  -0.2794154982]
         [                                                             ]
         [1  -0.6536436209  -0.7568024953  -0.1455000338   0.9893582466]
         [                                                             ]
    M := [1   0.2836621855  -0.9589242747  -0.8390715291  -0.5440211109]
         [                                                             ]
         [1   0.9601702867  -0.2794154982   0.8438539587  -0.5365729180]
         [                                                             ]
         [1   0.7539022543   0.6569865987   0.1367372182   0.9906073557]
         [                                                             ]
         [1  -0.1455000338   0.9893582466  -0.9576594803  -0.2879033167]
         [                                                             ]
         [1  -0.9111302619   0.4121184852   0.6603167082  -0.7509872468]

# Now find the least squares solution, the result of which are approximate
# values for the 5 unknowns in `varvec`.
#

C := LinearAlgebra:-LeastSquares( M, ydata );

                             [0.0000897022769103875]
                             [                     ]
                             [     2.61796597219174]
                             [                     ]
                        C := [     1.07445085124322]
                             [                     ]
                             [  -0.0131699592951893]
                             [                     ]
                             [   0.0796678388801930]

# Using those 5 solution values in place of the 5 unknown parameters in `varvec` gives us
# the solution: a formula for y as a function of x.
#

sol := r . C;
         sol := 0.0000897022769103875 + 2.61796597219174 cos(x)

            + 1.07445085124322 sin(x) - 0.0131699592951893 cos(2 x)

            + 0.0796678388801930 sin(2 x)

plots:-display(
  plots:-pointplot( <xdata|ydata>, symbolsize=15, color=blue ),
  plot( sol, x=min(xdata)..max(xdata) )
              );

acer

How about just passing `values` from `MCN` to `Display`?

restart:

Display:= proc(fin::list(indexed=nonnegint),values)
  local S,e;
  S := `%+`(seq(`if`(rhs(e)=0, [][],
                     `if`(rhs(e)=1, values[op(lhs(e))],
                          `%*`(values[op(lhs(e))], rhs(e)))
                     ),
                e = fin));
  InertForm:-Display(InertForm:-Value(S) = S)
end proc:

MCN := proc(values::list)
  local a, N, const, tval, res;
  N := nops(values); const := add(x[i], i = 1 .. N) <= 30;
  tval := add(x[i]*values[i], i = 1 .. N); 
  for a from 100 by -1 to 1 do 
    try
      res := Optimization:-LPSolve(tval, {tval = a, const},
                                   assume = {nonnegint}, depthlimit = 200) 
    catch "no feasible integer point found": 
      return a,Display(res[2],values);
    catch "no feasible point found for LP subproblem":
      return a,Display(res[2],values);
    catch:
      error;
    end try;
  end do;
end proc:

MCN([6, 9, 20]);

acer

You have overlooked that you are trying to access a command from a package.

Either call it as LinearAlgebra:-RowSpace(...) or load the package before using it. For example,

with(LinearAlgebra):
RowSpace(...);

acer

In 2D math input mode, type \ (ie. the backslash key) before typing _ (ie. underscore, usually Shift-minus keystrokes) in order to have the underscore symbols be displayed literally.

That should work before and after Maple 17. In Maple 16 and earlier typing a single underscore would lower the prompt to the subscript position. In Maple 17 and later that happens when two underscores are typed in succession.

You can often use the resulting name as intended, even when it's inadvertantly displayed as a subscript in the input. But it looks weird afterwards, and may be confusing if you come back to the Document at a later date. Using the backslash helps it look as intended, with underscores displayed literally.

See the help topic tasks/building/annotate/mathModeShortcut , or the table entry on escaping characters in the help topic worksheet/documenting/2DMathShortcutKeys .

acer

The `int` command provides an option `AllSolutions` which allows it to attempt and return a piecewise solution with conditions on parameters in the range of integration.

For this example this produces results equivalent to what one gets under assumptions. The result for the case x<0 is the same as what I get under assumptions if I also call `simplify`(...under the same assumption on x).

If you set up the call to `int` or `Int` yourself then this can be done by adding the option `AllSolutions`. The alternate spelling as `allsolutions` is also ok.

restart:

ee := Int((x-tau)^(0.5-1)*(tau^2+(tau^(1.5))*(8/(3))-tau-(2)*tau^0.5),
                         tau=0..x, allsolutions):

value(ee);

value( convert(ee,rational) );

If the integral call was produced by some other command then you can also enable this behavior with an environment variable (so that you don't have to mess with `op` in order to shoehorn that option into the `int` or `Int` call).

restart:

ee := Int((x-tau)^(0.5-1)*(tau^2+(tau^(1.5))*(8/(3))-tau-(2)*tau^0.5),
                         tau=0..x):

_EnvAllSolutions:=true:

value(ee);

value( convert(ee,rational) );

That all works in my Maple 18.01.

The result in the piecewise solution for condition x<=0 evaluates to zero for x=0 (the empty integration range). When I tried this example using assumptions on x instead of the `AllSolutions` option I could get a direct result for the assumption x<0 but not for x≤0.

acer

In a Document, apply a context-menu operation to either 2D Math input of output. This produces a black right-arrow and a result.

Now select the right-arrow and the output beside it with the mouse cursor. Then from the GUI's main menu select View , and Expand Execution Group

The hidden command that was applied, as the context-menu action, should be revealed.

On my Linux, those main menu choice are available as the keyboard acceleration, Alt-v then x

acer

Welcome to the site. Welcome to Maple! It's not as hard to use as it might seem at first.

There were several errors in your code, as you guessed.

There were mismatched start- and endbraces in both lambda1 and lambda2.

The assignments to R[0] and R[1] were just equations with `=`, not actual assignments with `:=`.

You were assigning to `R` after assigning to R[0] and R[1]. Assigning to `R` will wipe out those assignments to R[0] and R[1].

You were mixing up expressions and operators. You had `R` defined as an operator, but then were using it with `subs` as if it were an expression.

Here is a way, with RR as an expression.

restart:
f := .25; g := 1; R[0] := 5; R[1] := 4.8; nDays := 30;
lambda1 := (1 - f + sqrt((1 - f) + 4*g*f))*1/2;
lambda2 := (1 - f - sqrt((1 - f) + 4*g*f))*1/2;
k1 := (-lambda2*R[0] + R[1] )/(lambda1 - lambda2);
k2 := ( lambda2*R[0] - R[1])/(lambda1 - lambda2);
RR := k1*lambda1^N + k2*lambda2^N;
for n from 2 to nDays do
  evalf(subs(N=n,RR));
end do;

Here is a way, with RR as an operator.

restart:
f := .25; g := 1; R[0] := 5; R[1] := 4.8; nDays := 30;
lambda1 := (1 - f + sqrt((1 - f) + 4*g*f))*1/2;
lambda2 := (1 - f - sqrt((1 - f) + 4*g*f))*1/2;
k1 := (-lambda2*R[0] + R[1] )/(lambda1 - lambda2);
k2 := ( lambda2*R[0] - R[1])/(lambda1 - lambda2);
RR := N -> k1*lambda1^N + k2*lambda2^N;
for n from 2 to nDays do
  evalf(RR(n));
end do;

I suggest you study Robert Israel's great post of Top Ten Maple Errors.

acer

If you are in an Execution Group then the command from a right-click context-menu action is inserted as 1D Maple Notation, and then that gets executed. This happens whether you right-click on 2D Math input or 2D Math output.

If you are in a paragraph in a Presentation/Document Block then the command used by a right-click context-menu action is not visible as an explicit command. In later versions of Maple (including Maple 15) the inserted right-arrow may also be annoted, as a GUI preference. But that's not the same as giving you the actual command executed.

It's possible to insert an Execution Group (red cursor prompt, red input by default) in a Document, but it is awkward.

So if you like the context-menus and want to see commands used by them, explicitly, then you might find it much easier to use Worksheets rather than Documents.

acer

You can either enter the command yourself, or you can use the right-click context-menu which has an entry for taking limits.

Here is how it can look, by entering the commands yourself,

ee := ((2 + x)^3 +8)/x;

                                          3    
                                   (2 + x)  + 8
                             ee := ------------
                                        x      

limit(ee, x=0);

                                  undefined

limit(ee, x=0, right);

                                  infinity

limit(ee, x=0, left);

                                  -infinity

You can also use the Limit Tutor. From the main menubar select Tools -> Tutors -> Calculus - Single Variable, -> Limit Methods.

acer

expr := x + y + z;
                               expr := x + y + z

convert(expr,`*`);
                                     x y z

convert(expr,list);
                                   [x, y, z]

`*`( op(expr) ); 
                                     x y z

[ op(expr) ];    
                                   [x, y, z]

It wasn't clear whether you want to transform expr into both, or run through them as follows.

x + y + z;
                                   x + y + z

convert(%,`*`); 
                                     x y z

convert(%,list);
                                   [x, y, z]

x + y + z;
                                   x + y + z

`*`(op(%));
                                     x y z

[op(%)];   
                                   [x, y, z]

All you need to know here is that `op` returns the operands of a sum or product of terms. (I use the terms sum and product in the mathematical sense rather than in the sense of commands `sum` and `product`.) So `op` produces the expression sequence x,y,z when applied to either the sum or the product.

acer

You haven't told us your purpoise, so we have to guess.

restart:

tneighbors := proc(G::Graph)
  uses GraphTheory;
  local i, V;
  V := Vertices(G);
  {seq(`if`(nops(Neighbors(G,V[i]))=2, i, NULL), i=1..nops(V))};
end proc:

with(GraphTheory):

G1 := Graph( Trail(1,2,3,4,5,6,7,8,9,10,1), Trail(11,12,6,11,1,12) ):
#DrawPlanar(G1);

tneighbors( G1 );

                   {2, 3, 4, 5, 7, 8, 9, 10}

select(v->nops(Neighbors(G1,v))=2, {op(Vertices(G1))});

                   {2, 3, 4, 5, 7, 8, 9, 10}

# This kind of thing is generally suboptimal, as the quadratic memory
# cost of augmenting a set is unnecessary.
tneighbors2 := proc(G::Graph)
  uses GraphTheory;
  local i, S, V;
  V := Vertices(G);
  S := {}:
  for i from 1 to nops(V) do
    if nops(Neighbors(G,V[i]))=2 then
      S := S union {i};
    end if;
  end do;
  return S;
end proc:

tneighbors2( G1 );

                   {2, 3, 4, 5, 7, 8, 9, 10}

tneighbors3 := proc(G::Graph)
  uses GraphTheory;
  local i, T, V;
  V := Vertices(G);
  for i from 1 to nops(V) do
    if nops(Neighbors(G,V[i]))=2 then
      T[i] := i;
    end if;
  end do;
  return {indices(T,nolist)};
end proc:

tneighbors3( G1 );

                   {2, 3, 4, 5, 7, 8, 9, 10}

acer

The NAG quadrature solvers such as _d01amc have hard-coded weights that are only suitable for handling a double-precision approximation of each evaluation of the integrand. That's why evalf/Int won't let one use those methods with Digits greater than evalhf(Digits), or with the option `digits=d` and `d` that high.

And on the surface it may seem like this always means an insurmountable wall for integrands with subexpressions which may evaluate to outside the double-precision range, or for integrands which suffer from great roundoff error.

Also, when these methods were first introduced the evaluations of the integrand (a callback from NAG to Maple) were only allowed in `evalhf` mode.

But it is possible (since I forget when... Maple 9?, 10?) to use a non-evalhf'able procedure as the integrand with the three NAG univariate quadrature methods. Such a procedure is free to manage Digits internal to itself.

So two things could then happen, for such a procedure. Roundoff error in the individual integrand approximations might be reigned in. And values outside the usual 1e-308 to 1e308 range might be handled.

Having said that, it's often a good idea to keep the working precision of the rest of the solver as high as it can go (option digits=15) while allowing the tolerance (epsilon) to be relaxed optionally.

This seems enough to be able to get quick results for the various parameter pair values given. It's not going to solve all other numerically hard problems, but it seems to be adequate here.

The following results appear to match what others found (even with alternate, slow methods). But they compute quickly.

restart:

expr := exp(-x)^j*(1-exp(-x))^(4-j)*beta^alpha
        /GAMMA(alpha)*x^(alpha-1)*exp(-beta*x):

G:=proc(A, B, J, ee, {eps::float:=1e-14})
  local f;
  f:=subs(__DUMMY=eval(ee,[alpha=A,beta=B,j=J]),
          proc(x) Digits=50; []; __DUMMY;
          end proc);
  forget(evalf); forget(`evalf/int`);
  evalf(Int(f, 0..infinity, ':-digits'=15, ':-epsilon'=eps,
            ':-method'=':-_d01amc'));
end proc:

CodeTools:-Usage(
   seq( 'G'( 900, 50, j, expr ), j=0..4 )
                );

memory used=1.97KiB, alloc change=0 bytes, cpu time=0ns, real time=1000.00us, gc time=0ns

                                          -8                     -21  
    0.999999927237869, 1.81905311687842 10  , 4.25712142901189 10   , 

                         -27                     -33
      2.19976264687971 10   , 1.13667316831278 10   

CodeTools:-Usage(
   seq( 'G'( 45.2895968537810, 6.34934081467530, j, expr ), j=0..4 )
                );

memory used=2.22KiB, alloc change=0 bytes, cpu time=0ns, real time=0ns, gc time=0ns

    0.994712351662338, 0.00131579418350684, 0.00000406276781217926, 

                         -8                     -10
      2.42436962707272 10  , 2.45623513060466 10   

CodeTools:-Usage(
   seq( 'G'( 0.1, 50, j, expr, eps=1e-9 ), j=0..4 )
                );

memory used=2.29KiB, alloc change=0 bytes, cpu time=0ns, real time=0ns, gc time=0ns

                       -8                          
    9.76825547933535 10  , 0.00000158951838518320, 

      0.0000389398475682795, 0.00185661752266041, 0.992333435120739

## This will force 100 calls to G, taking 11.75 sec total on my i7
#CodeTools:-Usage(
#   plot( 'G'( a, 50, 2, expr ), a=0.1..100, adaptive=false, numpoints=100 )
#                );
## ## This will force 100 calls to G, taking 9.27 sec total on my i7
#CodeTools:-Usage(
#   plot( 'G'( a, 6.35, 2, expr ), a=40..50, adaptive=false, numpoints=100 )
#                );

The only fly in the ointment I saw was the case of high j=4 in the original example or alpha=0.1, beta=50. I found that case could be handled quickly, even at epsilon=1e-10, by a change of variables turning the range into t=0..1.

Lastly, I hard-coded Digits=50 into that procedure `G`. But it could alternatively be made an option of `G`, if it needed increasing.

 

acer

I don't think that it's easier to write a procedure for what is essentially a single command.

eq := f(z) = g(z):

map(Int, eq*K, z=1..L);       

                           L                L
                          /                /
                         |                |
                         |   K f(z) dz =  |   K g(z) dz
                         |                |
                        /                /
                          1                1

Replace `Int` with `int` if you want it active.

A procedure might make it easier if you didn't know yet what the name of the variable (of integration) was in the expressions on both sides of the equation. But if you already know the name of the variable of integration, the multiplicand K, the equation, and the range of integration then it's as simple to execute the command above as it is to call a procedure, no?

acer

First 237 238 239 240 241 242 243 Last Page 239 of 337