Carl Love

Carl Love

28095 Reputation

25 Badges

13 years, 100 days
Himself
Wayland, Massachusetts, United States
My name was formerly Carl Devore.

MaplePrimes Activity


These are answers submitted by Carl Love

This Answer is to answer the OP's followup question requesting a procedure that determines whether an arbitrary polynomial can be produced as a linear combination of a set of polynomials, and, if so, returning the coefficients.

I decided that it would be better to just write a separate procedure for this rather than rolling it into my procedure LinearCombo from an earlier thread. So I wrote a little procedure PolyLinearCombo that calls my version of Kitonum's CoeffsOfLinComb. I changed the declaration-of-variables argument to be optional; by default, all nonconstant names will be considered variables. If you want to use parameters, then include the variables argument as a set.

For various reasons, it's better that a procedure always return the same number of return values. So, this procedure returns true and a list of coefficients if the second argument can be produced as a linear combination of the elements of the first argument, and it returns false, [] if there's no such combination.

I decided to disallow 0 as the second argument. If you want nontrivial coefficients to produce 0, then just call CoeffsOfLinComb.

CoeffsOfLinComb:= proc(
     L::list(polynom),
     V::set(name):= indets(L, And(name, Not(constant)))
)
local
     c, k, C:= {c[k] $ k= 1..nops(L)},
     S:= solve({coeffs(expand(`+`((C*~L)[])), V)}, C),
     F:= indets(rhs~(S), name) intersect C=~ 1
;
     eval([C[]], eval(S,F) union F)
end proc:


PolyLinearCombo:= proc(
     F::list(polynom),
     f::And(polynom, Not(identical(0))),
     V::set(name):= indets([F,f], And(name, Not(constant)))
)
local C:= CoeffsOfLinComb([f, F[]], V);
     if C[1]=0 then (false, []) else (true, -C[2..] /~ C[1]) end if
end proc:

Examples of use:

Dependent example:

F:= ['randpoly([x,y])' $ 22]:
f:= randpoly([x,y]):
C:= PolyLinearCombo(F, f, {x,y});

Independent example:

F:= ['randpoly([x,y])' $ 22]:
f:= randpoly([z,y]):
C:= PolyLinearCombo(F, f, {x,y,z});

The above example becomes dependent if z is treated as a parameter:

F:= ['randpoly([x,y])' $ 22]:
f:= randpoly([z,y]):
C:= PolyLinearCombo(F, f, {x,y});

I'd condsider this a bug: The value of Digits and other environment variables (which have been modified from their defaults) should be transcribed to all nodes. Another workaround is to put

Digits:= 30;

into your initialization file.

I agree with Roman that you should run the evalf also in parallel; timewise, it is a significant part of the computation. But I do not agree that you should necessarily use numeric integration. So, change the Mapped procedure from int to evalf@Int or evalf@int depending on whether you want to use numeric or symbolic integration.

Your problem is that pdf1(i), etc., will evaluate to a numeric value even if i is symbolic (i.e., even if i has no numeric value). There are two ways to correct this. The preferred way is to make the following the first executable line of pdf1:

if not x::numeric then return 'procname'(args) end if;

The crude way is to put unevaluation quotes around the call to pdf1:

Sum('pdf1'(i), i= 3..3),

etc.

There is no bug.

The subtleties of unevauation-quote syntax can be mind-boggling. In this case, I find it easiest to take advantage of the fact that Explore's first argument is automatically unevaluated (see showstat(Explore, 1) or op([1,1], eval(Explore:-ModuleApply))) by wrapping all plots into the call to Explore. This can be done in a one-liner. I split the following command over a few lines so that it would display nicely on MaplePrimes, but it'll easily fit on one line in a Maple worksheet:

Explore(
     plots:-display(`<|>`(plot~([a*x^2, a*x^2+1], x= -1..1, y= -3..3)[])),
     parameters= [a= -1.0..1.0]
);

Syntax highlights:

`<|>`(1,2) is equivalent to < 1 | 2 >; it creates a row vector, which is sufficient for a side-by-side array of plots.

L[] converts list into its corresponding sequence. So `<|>`([1,2][]) is equivalent to < 1 | 2 >.

f~([a,b], c) is equivalent to map(f, [a,b], c) is equivalent to [f(a,c), f(b,c)].

For set complements, you could overload the exponentiation operator so that a set with superscript would represent the set complement. Indeed, it could all be put into a module constructed so that all the operations are done with respect to a particular universal set. So, below is essentially the same Answer that I gave before, but all the notations are shorter. I made `+` represent set union and `*` for intersection. I no longer feel that this is too trivial---the overloaded operators a were the missing piece.


restart:

SetOperations:= proc(U::set)
     module()
     option package;
     export
          `^`:= proc(A::set, e::identical(c), $)
          option overload;
               U minus A
          end proc,
          
          Select:= (f::procedure)-> select(f, U),
          
          `+`:= proc(A::set, B::set)
          option overload;
               A union B
          end proc,

          `*`:= proc(A::set, B::set)
          option overload;
               A intersect B
          end proc,
       
          P:= proc(A::set, B::set:= U, $)
               nops(A intersect B)/nops(B)
          end proc          
     ;
     end module
end proc:

TwoDice:= SetOperations({combinat:-permute([$1..6, $1..6], 2)[]}):
with(TwoDice);

[`*`, `+`, P, Select, `^`]

H:= Select(x-> :-`+`(x[]) = 5);

{[1, 4], [2, 3], [3, 2], [4, 1]}

G:= Select(x-> x[2] < 3);

{[1, 1], [1, 2], [2, 1], [2, 2], [3, 1], [3, 2], [4, 1], [4, 2], [5, 1], [5, 2], [6, 1], [6, 2]}

P(H);

1/9

P(G);

1/3

P(G^c);

2/3

P(H+G);

7/18

P(H*G);

1/18

P(G,H);

1/2

P(H,G);

1/6

#Law of total probability illustration

P(H) = P(H,G)*P(G) + P(H,G^c)*P(G^c);

1/9 = 1/9


Download prob.mw

 

 

You could use eval statements rather than assignment statements, like this

restart:
Z:= Matrix(2,2,symbol= z):
for k to 2 do
     Z||k:= eval(Z, z[k,k]= 1)
end do:
Z, Z1, Z2;

Thus, the values of and z never change. You're only making "working copies" of Z

Use P[A]:= 0.3, etc. For conditionals, use P[A,B].

The syntax f1(p,b):= ... is not the correct way to define a function in Maple. The correct syntax is 

f1:= (p,b)-> 1/(p^2 + b^2)^2;

Then enter the integral as 

T1pbm:= int(q*f1(q,b)*ln((p+q)^2 +m^2), q= 0..infinity) assuming real;

Notice that int is with a lowercase i. The integral will take 5-10 seconds. Then do the same for the second integral. It will take several minutes.

Since the integrals will be done, the calls to Parts will be superfluous. Since your variables have no numeric values, the calls to evalf are superfluous. Finally, the constant Pi is spelled with a capital P in Maple; pi is just another variable.

The equals sign is not the assignment operator in Maple, so your line in the for loop is not setting the values of A[0] and A[1]. The assignment operator is colon-equals. So, you simply need to change the line in the for loop to 

A[n] := int(...)

Here's a completely different algorithm. By evaluating the equation

f - add(c[k]*g||k, k= 1..m) = 0  (*)

at different exact random numeric evaluations of the variables xy, ..., we obtain a set of constant-coefficient linear equations in unknowns c[1], ..., c[m]. This system is solved. If there's no solution, then there's no linear combination (guaranteed). If there's a solution, it's used in a symbolic attempt to reduce (*) to 0=0. If this is possible, then it's a linear combination (guaranteed).

This algorithm works over a class of expressions much larger than polynomials, and it handles transcendental coefficients. Here it is:

LinearCombo:= proc(B::list(algebraic), T::algebraic)
local
     V:= indets([B,T], And(name, Not(constant))),
     nV:= nops(V),
     c, #linear coeffiecients
     k, K, #indices
     nB:= nops(B),
     Eq:= add(c[k]*B[k], k= 1..nB) - T,
     Eqs,
     S, Z, R
;
     for K to 2 do
          Eqs:= {'eval(Eq, V=~ {'rand()' $ nV})' $ nB};
          if nops(Eqs) = nB then break end if;
     end do;
     if K = 3 then
          error "Almost certainly, all expressions are constant"
     end if;
     S:= solve(Eqs);
     if S=[][] then return false end if;
     Z:= indets(rhs~(S), And(name, Not(constant)))=~ 0;
     S:= eval(S,Z) union Z;
     R:= is(eval(Eq,S) = 0);
    `if`(R, eval([c[k] $ k= 1..nB], S), R)    
end proc:

The procedure is called liked this:

LinearCombo([y^2-y, y+x^2], x^2+y^2);

Other than errors for syntactically incorrect input or system problems, it returns one of four things:

  1. a list of coefficients that make a linear combination
  2. false, indicating that no linear combination exists
  3. rarely, FAIL, indicating the inability of is to simplify the coefficients
  4. the error message Almost certainly, all expressions are constant.

A positive result (1) is guaranteed correct (it's been verified with is). A false result can be wrong with a small probability if there is a highly convoluted relationship among coefficients containing transcendentals that is incorrectly labelled false by is. The result FAIL, of course, can never be wrong, and it represents a failure of is (see ?is). If the error "Almost certainly, all expressions are constant" is returned, there is an infintesimal probability that two sets of m random evaluations of the variables just happened to pick values such that an equation was redundant.

Comments welcomed, especially attempts to break the program or interesting experiences with transcendental functions, transcendental coefficients, trigonometric and other identities.

You simply need to enclose the variable name in curly braces in the call to solve: Change 

solve(ics[i], v[i])

to

solve(ics[i], {v[i]})

Here's an efficiency/stylistic point, not an error: Unless you're planning on using the values solved[i] later, there's no point in storing them in variables. It just creates uncollectable garbage. Instead, combine the solve and assign:

for i to 3 do assign(solve(ics[i], {v[i]})) end do

 

It is an unfortunate nuance of the syntax that any reasonable attempt to create an empty Matrix using square brackets creates a Matrix with one empty row. That is, it has one row and zero columns. Note that 

ColumnDimension([[1]]) <> ColumnDimension([[]]),

the former being 1 and the latter 0.

As far as I can tell, the only two reasonable ways to create a truly empty Matrix are

Matrix()Matrix(0), etc.

or the more primitive

rtable(1..0, 1..0, subtype= Matrix).

These will create Matrices with zero rows and zero columns.

You wrote that it is possible to write 3*h(2)+D(h)(2) as (Psi(2)+gamma)*h(2)+D(h)(2). That is not true: Psi(2) = 1 - gamma, so Psi(2)+gamma = 1, not 3. So, the expansion of Psi(2) as 1 - gamma is irrelevant in this case. But if you did want to turn off the automatic expansion of Psi(positive rational), use 

map2(Cache:-RemovePermanent, Psi, [[1],[2]]);

`Psi/constant`:= `Psi/constant`[1], 0, `Psi/constant`[3]:

If you want to also turn off the expansion of Psi(positive rationalthat is done by the expand command, use

expand(expandoff()):  expandoff(Psi):

Now execute the residue command:

residue((Psi(-z)+gamma)^2*h(z), z= 2);

     2*h(2)*Psi(3)+(D(h))(2)+2*h(2)*gamma

I see that you changed your Question, changing gamma to Eulergamma. This is wrong. Eulergamma is meaningless to Maple. The Euler constant is known to Maple simply as gamma.


Edit: Answer corrected due to a problem discovered by Markiyan below.

 

You were on the right track with your idea of guessing b. We just have to make that automatic and systematic. Imagine a real-valued function RSS of a real variable bRSS returns the residual sum of squares from doing a linear regression on the logarithms to find the values of A and c. (That linear regression is done by the command Statistics:-PowerFit; you don't need to take the logarithms yourself.) Then we use Maple's numerical minimizer to find the b that minimizes RSS.

I'll assume that you can come up with lower and upper bounds for b. If not, I'll need to modify my procedure a little. In the procedure below, the first argument is your two-column Matrix, and the second argument is the range of possible b values in the form min_val..max_valI haven't tested this procedure because I don't have any suitable data. If you send your Matrix and your b range, I'd be happy to test it.

Since t-b must be strictly positive, the upper bound for b must be strictly less than the minimum value of t. If you violate this, you'll get an error message.

RecenteredPowerFit:= proc(TW::Matrix, b_range::range(realcons))
local
     T:= TW[..,1], W:= TW[..,2],
     b:= Optimization:-NLPSolve(
          b-> Statistics:-PowerFit(T-~b, W, output= residualsumofsquares),
          b_range, method= branchandbound, objectivetarget= 0
     )[2][1],
     Res:= Statistics:-PowerFit(T-~b, W)
;
     ['A' = Res[1], ':-b' = b, 'c'= Res[2]]
end proc:

If you want the symbolic derivative to be defined at the knots, then the slopes on either side of the knot need to match exactly. Matching to 14 decimal places is not exactly. To get an exact match, use exact numbers in the input: change 2.2 to 11/5 and change 1.8 to 9/5. If you make this simple change, there'll be no undefined points for the derivative. These subleties would not make any difference if you were using numeric differentiation.

By the way, the syntax x(t):= ... is a substandard way to define a function in Maple. It can lead to trouble. The correct way is x:= t-> ....

 

First 258 259 260 261 262 263 264 Last Page 260 of 395