Carl Love

Carl Love

28060 Reputation

25 Badges

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

MaplePrimes Activity


These are answers submitted by Carl Love

Here's another way that returns more of the points so that you can have denser plots.

k1k2:= proc(U::posint, a::posint:= 10, b::posint:= 1)
local K1, K2, p:= 1, k1:= 0, k2:= 0;
    while p < U do
        p:= nextprime(p);
        if isprime(a*p+b) then 
            k2:= k2+1; K2[p]:= k2
        else 
            k1:= k1+1; K1[p]:= k1
        fi
    od;
    K1, K2
end proc
:
(K1,K2):= CodeTools:-Usage(k1k2(10^7)):
memory used=3.58GiB, alloc change=72.00MiB, 
cpu time=21.78s, real time=21.51s, gc time=1.78s

plot(
    [
        [seq([p,K2[p]], p= combinat:-randcomb({indices}(K2, nolist), 999))],
        [seq([p,K1[p]], p= combinat:-randcomb({indices}(K1, nolist), 999))]
    ],
    style= point, symbol= solidcircle, legend= [k2, k1]
);

1. What [-4, 2] X [-4, 5] means: It's a common mathematical notation (but not a Maple notation) to represent domains[*2] (such as an area over which to make a plot or calculate a double integral) as a Cartesian product[*1], such as [-4, 2] X [-4, 5]. This means the rectangle (including its interior) whose lower left corner is the point (x,y) = (-4,-4) and whose upper right corner is (x,y) = (2,5). The Maple notation for this is

x= -4..2, y= -4..5

or variables other than x and y may also be used.

[*1] Definition: Given two sets A and B, their Cartesian product, denoted B, is the set of all ordered pairs (ab) where a is in A and b is in B. This is one of the most-fundamental concepts of mathematics. The definition can be extended to any number of set factors, even infinite, but I won't go into that here.

[*2] The precise mathematical definition of domain varies according to the source, and any of those definitions involve topological concepts that I'd rather not go into here. For our purposes here, just think of it as a "blob" in the xy-plane. A more-detailed discussion can usually be found in a multivariable calculus textbook in the double-integrals chapter or section.
 

2What grid means in a plotting contextMany plotting commands have a grid option. In a two-dimensional situation, such as with implicitplot, this is a list of 2 positive integers such as grid= [25,25] that represents the specific points within the plotting domain where the underlying computations are done. For the specific example at hand, grid= [25,25] means that 25 evenly spaced x-values are chosen in the interval -4..2, and 25 evenly spaced y-values are chosen in -4..5, for a total of 25x25 = 625 evaluation points. (Note that the set of evaluation points is the Cartesian product of the sets of x- and y-values.) 

The grid option usually does not directly translate into something that can be seen definitively on a plot, unless the values given are unusually small. Rather, larger grid values tend to make smoother plots but require more computational effort. If you actually want to see a grid in the background of your plot, the option for that is gridlines.
 

3. What Grid meansGrid (with uppercase G) is a Maple package that has nothing to do with plotting nor even mathematics. It allows you to control several processors or CPUs simultaneously (i.e., a "grid" of processors) with little-to-no sharing of memory between the processes. There is also a package Threads that does similarly but with a high-degree of memory sharing. Using either of these packages requires significant programming skills.

For the examples where Maple did give a result, you used t as the independent variable but told the fourier command that x was the independent variable. 

Apparently, the PDEtools:-declare in your version of Maple isn't sophisticated enough to display (Ax)t. Apparently, this is fixed in Maple 2020. If you remove the declare, Maple can handle the mathematics fine without the fancy display.

For more perspective, look at showstat(`print/diff`) both before and after the declare command. In my Maple 2020.0, its number of numbered statements goes from 68 to 119 (and its byte count goes from 3200 to 5972). The major work that declare does is to modify this procedure. In Maple 2016.2, its number of numbered statements goes from 66 to 116 (and its byte count goes from 2895 to 5842). That extra statement ((119-68) - (116-66) = 1) is probably what makes the difference. 

I don't know if this is available in your version of Maple. Look up the help page
?DataFrame. If it's available, then you can do something like

S:= <0,9,8,0,7; 3,5,6,5,1; 1,0,0,3,2>:
fancyS:= DataFrame(
    S, 
    rows= [small, medium, large], 
    columns= [Rose, Teal, Plum, Sand, Peach]
);

An alternative with less programmatic flexibility but similar display, which'll definitely work in your version, is

fancyS:= <
     <<Rose | Teal | Plum | Sand | Peach>, S> |
     <``, small, medium, large>
>;

using the same S as in the first case.

The assumptions made by an assuming clause are only in effect for the command to which the clause is applied. On the other hand, assumptions made with the assume command remain until they are explicitly lifted.

In your particular case, this distinction happens to make no difference, but it could easily make a difference for another example.

The operator for noncommutative multiplication is . not *. This operator can be applied to symbolic entities, as in

A.B + B.A

However, other than that, Maple has little-to-no support for symbolic linear algebra, and the transpose of a symbolic variable is just itself.

@ VV's Answer using LPSolve solves this problem as an integer linear program (ILP) using the branch-and-bound method. A few further details can be obtained by setting 

infolevel[Optimization]:= 5:

before running LPSolve, and by reading the help pages
?Optimization,LPSolve and ?Optimization,General,Options.

I believe (not sure) that LPSolve does not guarantee the true optimal solution for ILPs. Certainly I've seen several examples where the returned solution is not the true optimum; I don't know whether these should be considered bugs. The returned value and the time required to return it are very sensitive to the options depthlimitnodelimit, and integertolerance. Also, some randomization seems to be used because solutions sometimes vary based on the current randomize key.

Your problem (assuming that the initial array of numbers is always nonnegative) is a variation of the well-known and very important knapsack problem (see Wikipedia article linked). Specifically, it's a zero-one knapsack problem where the weights equal the pay-off values and the capacity of the knapsack is the sum of the weights minus the target value (the 5.2 in this case). The solution in this case is the items not put in the knapsack.

The are numerous algorithms specifically for knapsack problems, as the Wikipedia article details. LPSolve doesn't use these tailored algorithms, so better performance may be possible by coding an ad hoc method. But the theoretical complexity of the problem is at least NP-complete, if not NP-hard, in n, the number of weights, regardless of the algorithm used.

Some of the algorithms are parallelizable under Threads. For example, the algorithm that checks all subsets of weights is easily parallelizable.

 

To ban repeats, use

Z::And(list(identical(a,b,c,d)), 2 &under nops, 2 &under (nops@{op}))

The second clause restricts list length to 2. The third clause says that the length should still be 2 even if were converted to a set. Those clauses could be combined as

Z::And(list(identical(a,b,c,d)), [2,2] &under [nops, nops@{op}])

In the second procedure, the line a:= b causes a to be an implicit local (for the entire execution of the procedure), so it no longer has any connection to the global a. It's not the mere presence of a that makes it implicit local, it's that you make an assignment to it. Since the first procedure does not assign to a, global a is used. If you want a to be global in the second procedure, either declare global a, or use it as :-a.

Advice: Whenever you get a message about implicit locals, correct the code immediately.

Suppose that is your polynomial, is its set of coefficients, and S is the set of coefficients that you want to keep. Then do

eval(P, (C minus S)=~ 0)

If for some reason it's more convenient to store and S as lists, then do

eval(P, ({C[]} minus {S[]})=~ 0)

For large-scale programs it may be desirable to minimize list/set conversions.

 

SumList:= proc(L::{list, set})
local r:= 0, x;
    for x in L do r+= x od;
    r
end proc:

Factorial:= (n::nonnegint)-> local r:= 1, k:= 0; do r*= ++k until k>=n;

while loop could just as well be used in the second procedure. I just wanted to show you the possibility of an until loop. Since a do-until loop is guaranteed to execute at least once, the second procedure doesn't need to specify a return value after the loop.

g:= x-> 'g'(-x):

Or, starting from a known function f, its even part is

g:= x-> (f(x)+f(-x))/2:

These solutions use Maple tables, and they work for any modulus (your 8). 

PrimesByClass:= proc(N::posint, m::posint)
local p:= 2, L;
    while (p:= nextprime(p)) < N do L[irem(p,m)][p]:= () od;
    [indices]~(L, 'nolist')
end proc
:
CountPrimesByClass:= proc(N::posint, m::posint)
local p:= 2, L:= table(sparse);
    while (p:= nextprime(p)) < N do L[irem(p,m)]++ od;
    [indices](L, 'pairs', 'indexorder')
end proc
:
MaxClass:= (L::list(anything=realcons))-> lhs(L[max[index](rhs~(L))])
:
L:= PrimesByClass(100,8);
L:= TABLE([1 = [17, 41, 73, 89, 97], 3 = [3, 11, 19, 43, 59, 67, 83], 
  5 = [5, 13, 29, 37, 53, 61], 7 = [7, 23, 31, 47, 79, 71]])

CountPrimesByClass(100,8);
                  [1 = 5, 3 = 7, 5 = 6, 7 = 6]

MaxClass(CountPrimesByClass(10^6, 8)); 
                               7

 

@radaar wrote:

  • restart;
    i:=2:
    ff:=proc()
          i:=i+2:      #### implicit local 
          return i
    end proc:
    ff()

    output: i+2

    if we assign the output to another variable and try to output the variable it shows too many level of recursion

It's an interesting phenomenon. I wouldn't call it a bug, although I'd accuse a programmer who---through sloppy programming---relied on this to be creating their own bugs.

To analyze this, let's first cut away the bloat that has nothing to do with it:

  • That i has been globally assigned has nothing to do with this.
  • That the in the proc is implicitly local rather than declared local has nothing to do with this. Indeed, there's no runtime difference between the two, and a clean programmer should never rely on implicit locals.
  • Explicit return statements aren't needed.
  • Procedures don't need names; they can be anonymous.
  • Whether the output is assigned to another variable is irrelevant.
  • It's totally legitimate for a procedure to return an unevaluated local or an expression containing such. Such a local is called an escaped local. That local can happily live in the same lexical space as the global whose name is spelled the same. Indeed, there's a command specifically for creating such a local: convert(..., `local`). It'd be very instructive for you to study the very brief code of this command: showstat(`convert/local`). I recall that deconstructing that really opened my mind when I was first learning Maple.

Okay, let's look at some examples that all generate related error messages:

restart;
i:= i+2;

Are you satisfied that that causes a "recursive assignment" error? I am. If you truly want to use recursive assigments (at the top level), this works:

i:= ' 'i' + 2';
seq(eval(i, k), k= 1..9);

I find that to be a useful way to experiment with complicated recurrence relations because it gives you the ability to "single step" through them---no debugger needed.

Your example:

restart: #This is identical to your example, without the bloat:
proc() local i; i:= i+2 end proc();
%;

The exact same thing can be done with a global:

restart;
proc() :-i:= :-i + 2 end proc();
%;

Both give the "too many levels of recursion" error.  Are you satisfied with that?
 

Your examples are straying far enough away from your original Question that I think that they deserve their own thread.

You will learn a lot by trying to remove from your examples any factors that are irrelevant to the observed phenomena---those factors that I called "bloat" above.

First 102 103 104 105 106 107 108 Last Page 104 of 395