Carl Love

Carl Love

28035 Reputation

25 Badges

12 years, 317 days
Himself
Wayland, Massachusetts, United States
My name was formerly Carl Devore.

MaplePrimes Activity


These are answers submitted by Carl Love

These numbers can be extracted very simply and quickly as map2(-op, 1, roots(numer(q))) and map2(-op, 1, roots(denom(q))) or a slight variation of those if you need the multiplicities and/or assignment to a[1]a[2], ..., b[1]b[2], .... 

To plot column Vector as a function of same-length column Vector X, simply do

plot(< X | A >);

I don't mean to disparage Mac Dude's Answer; certainly it is what one would use in most cases. However, it is so obvious that I'd be surprised if it hadn't already occurred to the OP. Thus, I wonder whether the OP had something else in mind: to express the iteration over two variables with a (single) loop. This is possible, and it can be done for an arbitrary number of variables.

The easiest case is when the set of desired n-tuples can be expressed as a Cartesian product A^for some set A. In the example that the OP gives, this would be {$1..10}^2. For these cases, combinat:-permute can be used. Like this:

for ij in combinat:-permute(op~([[$1..10] $ 2]), 2) do
     (i,j):= ij[];
     #rest of loop
end do:

Cases where the n-tuples are the Cartesian product of different sets can also be handled. This requires an auxillary procedure---a substitute for combinat:-permute---that returns the Cartesian product. Here is one such:

CartProdSeq := proc(L::seq(list))
local Seq,i,j;
option `Copyright (C) 2007, Joseph Riel. All rights reserved.`;
eval([subs(Seq=seq, foldl(Seq
                             , [cat(i,1..nargs)]
                             , seq(cat(i,j)=L[j],j=nargs..1,-1)
                            ))]);
end proc:

And an example of using that in a loop: Suppose we wish to vary from 1 to 10, j from 1 to 9, and k from 1 to 8:

for ijk in CartProdSeq([$1..10], [$1..9], [$1..8]) do
     (i,j,k):= ijk[];
       #rest of loop
end do:

 

MDD, 

Please test the procedures in the attached worksheet. The first procedure, Homogenize, does what you want to the list of polynomials, F. The second procedure, MDD, is just a trivial one-liner that allows for your distinguished single polynomial, f.


restart:

(* In these comments, by "monomial", I always mean a product of powers of variables
without the coefficients. The monomial of the constant term is 1.

This procedure takes a list of polynomials, F, and substitutes an ordered list
created variables for the monomials.
*)
Homogenize:= proc(
     F::list(polynom),
     V::list(name),
     T::ShortMonomialOrder,
     #The prefix of the names that will be substituted for the monomials
     prefix::symbol
)
local
     n:= nops(F),
     k, #integer index into F
     #All tables are indexed by the position in F: k
     Mons:= table(), #The monomials in F[k], with 1 changed to 0
     Cofs:= table(), #The coefficients of F[k]
     Cons:= table(sparse), #The constant term of F[k]
     p, #position of 1 or 0 in M or TM[k]
     M, #Monomials in F[k], or all monomials excluding 1
     m, #nops(M)
     AL, #The homogenized variable for the constant term; the prefix + the highest
         #numbered suffix; prefix||(m+1)
     S #Substitution list of homogenous variables for monomials
;
     for k to n do
          Cofs[k]:= [coeffs(F[k], V, 'M')];
          M:= [M];
          #If M has 1, we need to change it to 0 so that we can later
          #get just the nonconstant terms by multiplication.
          if member(1, M, 'p') then
               M:= subsop(p= 0, M);
               Cons[k]:= Cofs[k][p]
          end if;
          Mons[k]:= M[]
     end do;
     M:= sort(
          [({entries(Mons,'nolist')} minus {0})[]],
          (a,b)-> Groebner:-TestOrder(b,a,T)
     );
     m:= nops(M);
     S:= M=~ [A||(1..m)];
     AL:= A||(m+1);
     [seq(`+`((Cofs[k]*~subs(S,[Mons[k]]))[]) + Cons[k]*AL, k= 1..n)]
end proc:          
                

#A wrapper for the above procedure that allows for one distinguished polynomial
MDD:= (F,f)-> (R-> (R[1],R[2..]))(Homogenize([f,F[]],_rest)):
    

MDD's example:

F:= [a*x^2*y^2+3*b*x*z^3+4, y*z+x*z+c-1];
f:= x^2*y-x*z+x*y*z+z^3-4+b+y*z^2;
V:= [x,y,z]:

[a*x^2*y^2+3*b*x*z^3+4, x*z+y*z+c-1]

x^2*y+x*y*z+y*z^2+z^3-x*z+b-4

(ff,FF):= MDD(F, f, V, plex(V[]), A);

A2+A3-A5+A6+A8+(b-4)*A9, [A1*a+3*A4*b+4*A9, A5+A7+(c-1)*A9]

Roman's example:

Homogenize([a*x^2*y^2+b*x^2*y^2, a*x^2*y^2, b*x^2*y^2], [x,y], plex(x,y), A);

[(a+b)*A1, a*A1, b*A1]

 

``


Download Homogenize.mw

 

Symbolically eliminating the parameter is only possible in very special cases. (Whether this is such a case I don't wish to discuss in this Answer.) Cases where Y can be completely expressed as a function of X are so trivial that they rarely are used in practice. One obstacle is that a range of the parameter must be specified so that Y is indeed a function of X rather than there being possibly multiple Y for each X. However, if you do specify such a range of the parameter, then it may be possible to at least give a numerical procedure that expresses Y as a function of X. Here is one for your example:

X:= (theta)-> cos(theta) + 0.8e-1*cos(3.*theta):
Y:= (theta)-> -sin(theta)+ 0.8e-1*sin(3.*theta):

YY:= proc(XX::numeric, theta_range::range)
local theta;
     Y(fsolve(X(theta)=XX, theta= theta_range))
end proc:

plot('YY(XX, 0..Pi)', XX= -1..1);

This is crude, and can be improved with some error checking, such as making sure that the fsolve actually returns a numeric value. 

To correct the "too many levels of recursion" error, in the definition of function g0, change sum to add. The problem with sum is that it tries to simplify these horrendously long nested piecewise expressions using symbolic j. If you use add, then it only uses definite integer values of j, and the piecewise expressions can be immediately resolved.

Apply CylindricalAlgebraicDecompose separately to the numerator and denominator of your rational function. You can use numer(r) and denom(r) to extract the numerator and denominator of rational function r. In some cases, it may be beneficial to first use normal(...), as in denom(normal(r)). See ?numer for some examples.

If you don't want to go the simplify(..., symbolic) route---which can be risky---it's easy to have a one-liner procedure that extracts all the bases of `^` expressions and and sets them  > 0


restart:

AllBasesPositive:= e-> (map2(op, 1, indets(e,`^`)) >~ 0)[]:

 

z:= ((-u(f,g)+u(h,e))^(1/a))^a+ sin(x)^2+cos(x)^2;

((-u(f, g)+u(h, e))^(1/a))^a+sin(x)^2+cos(x)^2

simplify(z) assuming AllBasesPositive(z);

-u(f, g)+u(h, e)+1

simplify(z, power) assuming AllBasesPositive(z);

-u(f, g)+u(h, e)+sin(x)^2+cos(x)^2

 


Download AllBasesPositive.mw

Here's how to fix this error. I'll assume that you still have Maple 16 installed. If you don't, let me know, and I'll post here the necessary code.

There are three procedures necessary for your program that exist in Maple 16 that are missing in later Maple. Their names are zero_one, polyvariations, and midpoint. These procedures are defined when you execute the (deprecated) command readlib(realroot). We need to extract the code of these procedures from Maple 16 and put it in your code file. Here's how.

1. In a Maple 16 worksheet, issue the command

readlib(realroot):

2. Issue the command

showstat~([zero_one, polyvariations, midpoint]);

3. Using your favorite text editor (I used Microsoft Windows Notepad), cut-and-paste the code of the three procedures to the end of your code file proving.txt.

4. Using the text editor, remove the line numbers from the procedures, being very careful that you don't remove anything else. It's okay to remove or add spaces at the beginnings of lines.

5. Add a comment to your code about where these three procedures came from. Mention how they were extracted with readlib.

6. Save the file proving.txt.

7. Run your program in Maple 2015.

I have done this, and it works.

There may still be use instances of your program that lead to similar errors, or will eventually lead to similar errors in future editions of Maple. To help in finding those errors now rather than when those future editions come, I recommend that you comment out all uses of the command readlib and then do some rigorous testing of your program---something that uses all of its procedures.

Several changes were necessary to get this to work, all of which I point out in my modified worksheet below. Most significant is turning off hardware floats and specifying the inflection points of the distribution (see ?Statistics,Sample). It's a shame---an unnecessary limitation of Statistics:-Sample---that it does not automatically revert to software floating point if the hardware floating point doesn't work.

I redid your worksheet using 1D input because I can't tolerate the 2D input. I put my name in front of all my comments.

 

restart:

 

Carl: Maple will not be able to evaluate the derivative of the PDF using hardware floating point because the exponential values in the intermediate computations are too extreme (even though the final results are not too extreme). So, we force it to use software floating point. If this becomes a speed problem for you (because you need to sample millions of points, for example), let me know.

UseHardwareFloats:= false:

 

Normal distribution with a standard deviation relative to the mean.

NormalR:= (t,mu)-> exp(-(t-mu)^2/2/(mu/20)^2);

proc (t, mu) options operator, arrow; exp(-200*(t-mu)^2/mu^2) end proc

Create a truncation, both at the tails and in the center. To sample a PDF, the PDF should be twice differentiable (except at the tail-truncation). Use logistic functions.

Lot:= (t,mu,alpha,beta)-> 1/(1+exp(-mu/beta*((1-beta)*mu-t))) + 1/(1+exp(-mu/beta*(t-(1+beta)*mu)));

proc (t, mu, alpha, beta) options operator, arrow; 1/(1+exp(-mu*((1-beta)*mu-t)/beta))+1/(1+exp(-mu*(t-(1+beta)*mu)/beta)) end proc

plot(Lot(t, 10, 0.1, 0.01), t= 8.5..11.5);

Carl: Observe what happens on the small scale.

plot(Lot(t, 10, 0.1, 0.01), t= 9.89..9.91);

Carl: Observe that the inflection point is at 9.9. Likewise, there's an inflection point at 10.1.

 

Carl: Create the untruncated PDF.


LotR:= (t, mu, alpha, beta)-> NormalR(t, mu)*Lot(t, mu, alpha, beta);
plot(LotR(t, 10, 0.1, 0.01), t= 8.5..11.5);

proc (t, mu, alpha, beta) options operator, arrow; NormalR(t, mu)*Lot(t, mu, alpha, beta) end proc

Carl: Find inflection point on first up slope.

fsolve(diff(LotR(t,10,1/10,1/100), t$2), t= 8.5..9.9);

9.50000000000000

Carl: Likewise, there's an inflection point at 10.5.

 

The final distribution function.

 

Carl: Truncate and renormalize to get our final PDF. We want to do this in such a way that the integration isn't redone every time the PDF is used. Thus, it needs go be done as below, as a procedure that returns the result of an unapply.

LotRPDF:= (t::name, mu::numeric, alpha::positive, beta::positive)->  
     unapply(
          LotR(t, mu, alpha, beta) /
          evalf(Int(LotR(t,mu,alpha,beta), t= (1-alpha)*mu..(1+alpha)*mu)),
          t
     )
;

proc (t::name, mu::numeric, alpha::positive, beta::positive) options operator, arrow; unapply(LotR(t, mu, alpha, beta)/evalf(Int(LotR(t, mu, alpha, beta), t = (1-alpha)*mu .. (1+alpha)*mu)), t) end proc

Carl: Note that LotRPDF returns a procedure with parameter t rather than an expression in t

plot(LotRPDF(t, 10, 0.1, 0.01), 8.5..11.5);

Carl: Note that the PDF is only the part from 9..11. It's truncated. Verify:

evalf(Int(LotRPDF(t, 10, 0.1, 0.01), 9..11));

1.00000000000000

Carl: Make a procedure that returns a distribution. Note the Support argument: Providing is often not strictly necessary, but it vastly simplifies the computation required to use the distribution.

GetDist:= (mu,alpha,beta)->
     Statistics:-Distribution(
          PDF= LotRPDF(t, mu, alpha, beta),
          Support= (1-alpha)*mu..(1+alpha)*mu
     )
:

T:= GetDist(10, 0.1, 0.01):
Statistics:-DensityPlot(T);

RandomR:= Statistics:-RandomVariable(T);

_R0

Density plot is not a problem, however, computation of the Sample seems not to end.

 

Carl: We need to tell Sample the inflection points and the range. Then it will end. Note that the end result of this will be a procedure which can be used for all sampling rather just a sampled value.

SampleR:= Statistics:-Sample(
     T,
     method= [
          envelope,
          range= 9.00..11.00,
          #Inflection points
          basepoints= [9.5, 9.9, 10, 10.1, 10.5]
     ]
);

proc (n::Sample:-sizeType) local v, r, t; option `Copyright (c) Maplesoft, a division of Waterloo Maple Inc. 2004`; if UseHardwareFloats = 'deduced' then UseHardwareFloats := `if`(Digits <= trunc(evalhf(Digits)), true, false) end if; if UseHardwareFloats then Digits := `if`(Digits < trunc(evalhf(Digits)), trunc(evalhf(Digits)), Digits) end if; if type(n, ':-rtable') then v := n else if type(n, ':-nonnegint') then r := 1 .. n; t := ':-Vector'[':-row'] elif type(n, ':-range') then r := n; t := ':-Array' elif type(n, '[:-nonnegint, :-nonnegint]') then r := 1 .. n[1], 1 .. n[2]; t := ':-Matrix' else r := op(n); t := ':-Array' end if; v := rtable(r, ':-datatype' = ':-float', ':-subtype' = t, op([])) end if; mapleRandomSample(v, 'NULL', [[1, [proc (t) options operator, arrow; 1.00239102890660*exp(-2*(t-10)^2)*(1/(1+exp(-9900.00000000000+1000.00000000000*t))+1/(1+exp(-1000.00000000000*t+10100.0000000000))) end proc, proc (t) options operator, arrow; 1.00239102890660*(-4*t+40)*exp(-2*(t-10)^2)*(1/(1+exp(-9900.00000000000+1000.00000000000*t))+1/(1+exp(-1000.00000000000*t+10100.0000000000)))+1.00239102890660*exp(-2*(t-10)^2)*(-1000.00000000000*exp(-9900.00000000000+1000.00000000000*t)/(1+exp(-9900.00000000000+1000.00000000000*t))^2+1000.00000000000*exp(-1000.00000000000*t+10100.0000000000)/(1+exp(-1000.00000000000*t+10100.0000000000))^2) end proc, [9.00, 9.5, 9.9, 10., 10.1, 10.5, 11.00], 100, false]]], UseHardwareFloats); return v end proc

Carl: Generate 1 point.

SampleR(1);

Vector[row](1, {(1) = 10.4381592823491})

Carl: It would be nice if the range and basepoints were parametrized in terms of mu, alpha, and beta. But, I've done enough for now.

 

Download RandomVariableSample(2).mw

How about

M:= k-> Matrix(10, 10, [1$k, 0$10-k], scan= diagonal):
M(5);
'M(k)' $ 'k'= 1..10;

The evalf[n](exprdoesn't mean "give me the value of expr accurate to digits". Many users have that wrong impression. It means (approximately) that at least digits are used in all the subcomputations. That "give me the value..." thing is practically impossible to implement. For the reasons, see the first chapter of almost any textbook on numeric computation.

The code that you're running here is obviously intended to break or to highlight the deficiencies of floating-point computation systems.

As to your second question: Many Maple commands "remember" the values from earlier computations. So, if it knows that it already computed the desired result to a higher precision, it just re-uses that. The commands restart and forget make it forget what it has remembered (I recommend the restart).

Three points:

1. Don't set Digits as low as 5 unless that's necessary to get an answer. If you only want digits, just ignore the other digits. (There's also a command interface(displayprecision). The results of using that are visually hideous.) Stick with the default Digits10, or use my favorite "sweet spot", Digits = 15.

2. The command pade is in the package numapprox. To access it you need to refer to it as numapprox:-pade or numapprox[pade] or first issue the command with(numapprox). I strongly prefer the first of these three options.

3. solve will spend a long time trying to find exact solutions to this pair of high-degree polynomials---a likely impossible task. Use fsolve instead of solve to get decimal solutions. This only takes a few seconds. This will only give one solution. If you need more than one, let me know: For polynomial systems, it's usually easy to get all the solutions within any real bounding box.

So, change the last part of your your code to

fsolve({
     limit(numapprox:-pade(diff(f,x), x, [4,4]), x= infinity) = 1,
     limit(numapprox:-pade(t, x, [4,4]), x= infinity) = 0.
     }, {A,B}
);

     {A = -0.680502612209264e-1, B = -3.43533296567616}

Here's an even shorter and faster variant for returning the coefficient of particular term.

P:=a*x^2*y*z+b*x*y*z+c*x^2*y*z+d*x*y^2*z+e*x*y*z:
L:=[coeffs(P, [x,y,z], 't')]:

H:= table([t]=~L):
H[x^2*y*z];

       a + c

How about (assuming that alpha has a numeric value)

fracdiff(t^beta, t, alpha);

or, if alpha is symbolic, something like

fracdiff(t^beta, t, alpha) assuming alpha > 0, alpha < 1;

First 256 257 258 259 260 261 262 Last Page 258 of 395