acer

32405 Reputation

29 Badges

19 years, 351 days
Ontario, Canada

Social Networks and Content at Maplesoft.com

MaplePrimes Activity


These are answers submitted by acer

One of you queries seems to be about whether you can write a constructed GUI Table (such as Tabulate embeds in a worksheet) to a new and separate .mw file. Here is how you can do that, programatically.

restart;
M := LinearAlgebra:-RandomMatrix(5,2);

str := DocumentTools:-ContentToString(
         DocumentTools:-Layout:-Worksheet(
           DocumentTools:-Tabulate(M, widthmode=pixels,
                                      width=400,
                                      output=XML))):
#
# For fun, this displays it in a new GUI tab.
#
:-Worksheet:-Display( str );

#
# This writes the Table to a new .mw file.
#
# Edit the filename and location as you choose. You 
# certainly don't have to use TemporaryDirectory or
# TemporaryFilename.
#
fname := FileTools:-TemporaryFilename(
            cat(FileTools:-TemporaryDirectory(),"/"), ".mw" ):
FileTools:-Text:-WriteFile( fname, str ):

#
# For fun, you can display that file in a new GUI tab.
#
:-Worksheet:-DisplayFile( fname );

tabulate_mw.mw

That would allow you to get some nice color, headers, and even some formulas if you wanted. And I suspect that you might export the worksheet (manual right-click) to PDF format.

But you might also use printf alongside writeto (or appendto), or just fprintf, if you would be satisfied with a text file. Try Carl's suggestion to handle special characters in printf, but writing to your text file.

It's a bit tricky to answer here, without knowing precisely what are your final goals. Is it a full report, or just part of it? As text file? With the data accessible from the file, or not? Etc.

It may well assist you later on to understand that your central problem here is not due to the presence of a conditional.

In fact your code can be modified to work with if..then, as well as with piecewise.

The central problem was that the global name H in the expressions assigned to Rehf, PL1, and PL2 was not the same as the name H appearing as the parameter of your procedure. Hence neither the evaluation of Rehf in the conditional test nor the evaluation of PL1,PL2 were working as you wanted within that procedure.

It turns out that using piecewise is terser and neater than using if..then, and using an expression rather than a procedure is terser still. But the reason those work better that your original lies in how the name H is being evaluated, and not because you were wrong to use if..then.

And you could also have fixed up the evaluation within the procedure. or you could use unapply to construct a procedure with the same, matching instance of name H as parameter.

This whole evaluation issue is quite common. It was not an if...then problem. Your example just happened to involve a conditional. The original wouldn't have produced any plot even if it always returned just PL1.

These all work, because they fix the central problem of evaluation of H within Rehf, PL1, and PL2.

restart:
nuhf:=0.294*10^(-6):
Rehf:=Vhf*H/nuhf:
Vhf:=0.5:
rhohf:=965.31:
Lhs:=2.5*10^(-3):
DP1:=f1*Lhs*rhohf*Vhf^2/(2*H):
f1:=4*18.3/Rehf:
Whs:=1:
mhf:=rhohf*Vhf*Whs*H:
Rehf:=Vhf*H/nuhf:
PL1:=DP1*mhf/rhohf:
DP2:=f2*Lhs*rhohf*Vhf^2/(2*H):
f2:=0.3164/(Rehf^(0.25)):
PL2:=DP2*mhf/rhohf:

procd:=proc(H)
    if eval(Rehf,:-H=H)<1000 then
      eval(PL1,:-H=H);
    elif eval(Rehf,:-H=H)>1000 then
      eval(PL2,:-H=H);
    else
      0;
    fi;
end:
plot(procd, 0..0.002);
plot('procd(H)', H=0..0.002);

procd2:=unapply(piecewise(Rehf<1000, PL1, Rehf>1000, PL2),H):
plot(procd2, 0..0.002);
plot('procd2(H)', H=0..0.002);

exprd:=piecewise(Rehf<1000, PL1, Rehf>1000, PL2):
plot(exprd, H=0..0.002);

Here is one way, using a variant on your call to VolumeOfRevolution.

QuestionOptionVolume_ac.mw

Your methodology to check where the csgn is positive seems a consequence of your given example.

Why shouldn't there be some other example where the odetest result becomes zero when a csgn subexpression is negative, or when some mix of conditions attain due say to cancellation amongst several csgn instances?

What logical or mathematical justification do you have that you can generally find the conditions by examining only the arguments to csgn subexpressions? Why would that be valid?

[edit: I should be more clear. Your methodology, as presented, is generally invalid.]

Why not try to compute directly the solution to the actual problem of where res the odetest result becomes zero, possibly under the condition that x is real?

Perhaps you could start by trying something straightforward like, say,
    solve(simplify(res)) assuming real;
(possibly testing finite end-points of ranges, singletons, and singular points separately) and then trying to refine the approach when harder examples arise?

For example,

restart;
ode :=diff(y(x),x)=2*(x*sqrt(y(x))-1)*y(x):
ic  :=y(0)=1:
sol :=dsolve([ode,ic]):

res :=odetest(sol,ode):

lprint(res);
-2*x/(x+1)^3*csgn(1/(x+1))+2*x/(x+1)^3

solve(simplify(res)) assuming real;
                 RealRange(Open(-1), infinity)

note: The example you present is here the same as a followup example you just added to your previous Question on this same topic. In that thread I wrote about the matter of possible realness of the solution, and I made use of assuming it in my Answer's handling of several of your examples. That matter still seems germane.

Some of the narrow spikes in the integrand will get missed, and their (positive) contribution neglected.

The blue plot is just wrong. I don't think that the constant approximation G below is quite accurate enough, however. Perhaps it ought to be closer to 0.04409...

restart;
G:=evalf(Int((sin(t)^2)^exp(t), t=5..infinity));
                       G := 0.04401097083

F := Int(t->(sin(t)^2)^exp(t), x..5):
P1 := plot(F+G, x=-5..5, color=red, thickness=2, size=[500,300]);

f := Int(t->(sin(t)^2)^exp(t), x..infinity):
P2 := plot(f, x=-5..5, color=blue, thickness=2):
plots:-display(P1, P2, size=[600,600]);

Since the OP asked about numerical verification, here's a start on that.

It uses the fact that `evalf/D` calls the fdiff procedure, which does numeric differentiation.

I'm not going to get into specifying error tolerances and working precision.

Note the two different schemes for approximating the second derivative, one of which doesn't do as well.

restart;
DE := diff(y(x), x, x) = 1/y(x) - x*diff(y(x), x)/y(x)^2:
sol := dsolve({DE, y(0)=1, D(y)(0)=0}, numeric, output=listprocedure):
Y := eval(y(x), sol):
dY := eval(diff(y(x),x), sol):
#
# This evaluates the rhs of the DE using the dsolve/numeric
# approximation for both y(x) and diff(y(x),x) .
#
RHS := eval(eval(rhs(DE), diff(y(x),x)=dY(x)), y(x)=Y(x));
                             1     x dY(x)
                     RHS := ---- - -------
                            Y(x)        2 
                                    Y(x)  

#
# Under evalf/D this will numerically compute the
# first derivative of the dsolve/numeric approximation
# for diff(y(x),x), thus approximating the second
# derivative of y(x).
#
LHS1 := convert( eval(lhs(DE), diff(y(x),x)=dY(x)), D);
                        LHS1 := D(dY)(x)

#
# Under evalf/D this will numerically compute the
# second derivative of the dsolve/numeric approximation
# for y(x), thus approximating the second
# derivative of y(x). (This scheme does not do as well.)
#
LHS2 := convert( eval(lhs(DE), y(x)=Y(x)), D);
                     LHS2 := @@(D, 2)(Y)(x)

plot(LHS1-RHS, x=0..2, size=[500,200]);

plot(LHS2-RHS, x=0..2, size=[500,200]);

ode_evalf_D.mw

You can get smoother surfaces here by passing an increased value for the grid option.

Oloid_ac.mw

I also changed the color and the style, to try and show the smoother surfaces without the gridlines obscuring the improvement.

You almost always respond here with Replies, rather than Answers. That is not new behaviour.

A Reply cannot receive a thumb's-up or a vote, or best-Answer cup-icon. An Answer can. (I believe that this technically addresses your query.) This is just how the site's mechanisms currently work. That is not very new behaviour.

I usually/often change your Replies to Answers, when appropriate, which allows them the receive votes. I don't always do it.

I don't know why you invariably submit Replies rather than Answers. There are buttons for each, just below a Question's body.

There are many ways to go about this. It may depend upon whether you want to only display the results, how fancy you want to get it, or whether also to compute further with the values.

I'll repeat some operations here, to try and make some possibilities clearer.

restart;
T := t -> (t+459.47) * 5/9:

# a Vector of a sequence of values
V := <seq(t, t=100..250, 25.0)>;

# applying T, elementwise, to V
T~(V);

# two Vectors joined as a Matrix
M := < V | T~(V) >;

printf("\n%10.2f\n", M);

# with a header row
M := < < Unit(degF) | Unit(kelvin) >, < V | T~(V) > >:
M;

DocumentTools:-Tabulate(M, width=250, widthmode=pixels,
                        fillcolor=((M,i,j)->`if`(i=1,"LightBlue","Azure"))):

table_of_values.mw

For this example, would you accept an implicit (exact) solution, verified by implicit differentiation?

restart;

ee := diff(y(x),x,x) = 1/y(x) - x*diff(y(x),x)/y(x)^2;
impsol := dsolve(ee, implicit);

implicitdiff(eval(lhs(impsol),y(x)=y), y, x):
E1 := diff(y(x),x) = subs(y=y(x), %);
E2 := diff(y(x),x,x) = simplify( diff(rhs(E1), x) );

simplify( eval(eval((lhs-rhs)(ee),E2),E1) );

                   0

Another way to accomplish this is to construct them as names (entities).

This has an added benefit that they display directly in the Maple GUI without doublequotes when using regular print. As shown below, they also work with printf.

There are two choices for lowercase sigma. I have chosen the lowercase sigma σ, that is more often used in mathematics, rather than the lowercase sigma ς for word-final position.

restart;

Greek_uppers:=["Alpha","Beta","Gamma","Delta","Epsilon","Zeta","Eta", 
               "Theta","Iota","Kappa","Lambda","Mu","Nu","Xi","Omicron",
               "Pi","Rho","Sigma","Tau","Upsilon","Phi","Chi","Psi","Omega"]:
Greek_lowers:=map(StringTools:-LowerCase,Greek_uppers):
Greek:=table([seq(Greek_uppers[i]=nprintf(`&#%ld;`,912+i),i=1..17),
               seq(Greek_uppers[i]=nprintf(`&#%ld;`,912+i+1),i=18..24),
               seq(Greek_lowers[i]=nprintf(`&#%ld;`,944+i),i=1..17),
               seq(Greek_lowers[i]=nprintf(`&#%ld;`,944+i+1),i=18..24)]):

seq(printf(" %s  %s   %s\n", Greek[g], Greek[StringTools:-LowerCase(g)], g),g=Greek_uppers);
 Α  α   Alpha
 Β  β   Beta
 Γ  γ   Gamma
 Δ  δ   Delta
 Ε  ε   Epsilon
 Ζ  ζ   Zeta
 Η  η   Eta
 Θ  θ   Theta
 Ι  ι   Iota
 Κ  κ   Kappa
 Λ  λ   Lambda
 Μ  μ   Mu
 Ν  ν   Nu
 Ξ  ξ   Xi
 Ο  ο   Omicron
 Π  π   Pi
 Ρ  ρ   Rho
 Σ  σ   Sigma
 Τ  τ   Tau
 Υ  υ   Upsilon
 Φ  φ   Phi
 Χ  χ   Chi
 Ψ  ψ   Psi
 Ω  ω   Omega

note. I course, you can also easily convert the strings that Carl constructed into names, eg, convert(...,name) , etc.

[edit] Also, the methodology that Carl used, with the StringTools:-Char command, will also work in the plaintext console-driven Maple Command-Line Interface (CLI) and not just the Maple GUI.

For fun, see also this old Question.

You could look at the Help page for the unassign command.

It doesn't appear that Ag2O is one of the chemical names recognized by the ThermophysicalData package in current Maple.

Also, programmatically,

map(proc(s) `if`(StringTools:-Search("Ag",s)>0,s,NULL); end proc,
    ThermophysicalData:-Chemicals:-GetSpecies());

        ["Ag(g)", "Ag+(g)", "Ag-(g)", "Ag(cr)", "Ag(l)"]

The reference seems to be this:
McBride, Bonnie J.; Zehe, Michael J.; and Gordon, Sanford. NASA Glenn Coefficients
for Calculating Thermodynamic Properties of Individual Species; 2002

Why not try the factor command, to attempt to factor out a term of a common power?

expr := y^2+y^3*sin(x)+3*x*y^5;

                         2    3               5
                expr := y  + y  sin(x) + 3 x y 

aa := factor(expr);

                       2 /     3               \
                aa := y  \3 x y  + sin(x) y + 1/

For this example the factored form is not "smaller" by the metrics used by simplify. But you can avoid that with an option:

simplify(expr, size=false);

                    2 /     3               \
                   y  \3 x y  + sin(x) y + 1/

Fwiw, using these metrics,

H := ee->[`simplify/size/size`(ee),
          MmaTranslator:-Mma:-LeafCount(ee),length(ee)]:

H(expr), H(aa);

          [48, 16, 41], [48, 16, 45]

[edit] You can also use factor with frontend. That works for the example involving rational powers (radicals) you added in an edit to your Question (one of two ways which handle that example, which I showed in my Reply to that new information first presented under mmcdara's Answer).

You've stated a goal of factoring. So useful commands can include:

factor(...)
evala(Normal(...))
frontend(factor,...)
simplify(..., size=false)
simplify(...)
evala(Factor(...))

depending on your (as yet unstated) goal requirements, restrictions, and problem class.

Add the explicit option to your call to the solve command, if you want roots in terms of explicit radicals instead of implicit RootOf.

help_ac.mw

You could also read the Help page for topic solve,details.

First 98 99 100 101 102 103 104 Last Page 100 of 336