nm

11538 Reputation

20 Badges

13 years, 115 days

MaplePrimes Activity


These are replies submitted by nm

@WD0HHU 

use  n in {$1 .. 31} like this

TypeTools[AddType]( my_type_Month, n->evalb(n::integer and n in {$1 .. 31}));

 

my_proc := proc(a::integer, b::my_type_Month) print(b); end proc:

my_proc(3,15);

15

my_proc(3,32);

Error, invalid input: my_proc expects its 2nd argument, b, to be of type my_type_Month, but received 32

Download month_type.mw

or can also write    and n>0 and n<32

@Harry Garst 

google AI review also sometimes gives wrong Maple code. I asked it

             how to find distance between two points in Maple

And it said this

But this code in Maple 2024 does not work

restart;

with(geometry);
pointA := point(2, 3);
pointB := point(5, 7);
distance := Distance(pointA, pointB);

[Apollonius, AreCollinear, AreConcurrent, AreConcyclic, AreConjugate, AreHarmonic, AreOrthogonal, AreParallel, ArePerpendicular, AreSimilar, AreTangent, CircleOfSimilitude, CrossProduct, CrossRatio, DefinedAs, Equation, EulerCircle, EulerLine, ExteriorAngle, ExternalBisector, FindAngle, GergonnePoint, GlideReflection, HorizontalCoord, HorizontalName, InteriorAngle, IsEquilateral, IsOnCircle, IsOnLine, IsRightTriangle, MajorAxis, MakeSquare, MinorAxis, NagelPoint, OnSegment, ParallelLine, PedalTriangle, PerpenBisector, PerpendicularLine, Polar, Pole, RadicalAxis, RadicalCenter, RegularPolygon, RegularStarPolygon, SensedMagnitude, SimsonLine, SpiralRotation, StretchReflection, StretchRotation, TangentLine, VerticalCoord, VerticalName, altitude, apothem, area, asymptotes, bisector, center, centroid, circle, circumcircle, conic, convexhull, coordinates, detail, diagonal, diameter, dilatation, directrix, distance, draw, dsegment, ellipse, excircle, expansion, foci, focus, form, homology, homothety, hyperbola, incircle, inradius, intersection, inversion, line, medial, median, method, midpoint, orthocenter, parabola, perimeter, point, powerpc, projection, radius, randpoint, reciprocation, reflection, rotation, segment, sides, similitude, slope, square, stretch, tangentpc, translation, triangle, vertex, vertices]

Error, (in geometry:-point) wrong type of arguments

Error, (in geometry:-point) wrong type of arguments

Error, attempting to assign to `geometry:-distance` which is protected

 

 

Download wrong_AI_code.mw

Second example

Asked google "how to generate random integer in Maple" and google AI said

 

But when running the code Maple gives

restart;

random_number := rand(1, 10);

print(random_number);

Error, invalid input: too many and/or wrong type of arguments passed to rand; first unused argument is 10

random_number

 


 

Download ex2.mw

 

 

In these two cases, the solution obtained is formal, without analysing the cases when the coefficient of a variable is zero

isn't this how CAS systems work? They give generic solution. Here is Mathematica's answer for your first examples, same as what Maple gives

 

@acer 

Thanks, I did not know I can use $define. Will try that. 

I know I can put uses toX=some_very_long_name:-toX inside a proc like you did. But as I said, this toX is used in almost every proc in every module, and I did not want to put this in each proc and in each module.

I found I can use it at the top of the module and now each proc inside the module sees this short hand.

This saved me having to type uses toX=some_very_long_name:-toX as many times as there are proc's in the module.

As to your question about why I had to change all my modules to local, well, it is because your code which collects all names inside the main module, only collects ones that are local.

My set up was this

export A := module()
 
    export A0 := module()
       ...
    end module;

    export A2 := module()
       ...
    end module;

etc...

end module
     

But the above does not work in Grid, unless I manually pass/type all the names of each module inside the top level level module and pass them to Grid using the Set command. I am not oging to type in 100 names or so each time I call Grid.

So your code you wrote to my other question automatically finds all these names, which is nice, but it only works only when I changed all exports to local, like this

export A := module() 

    local A0 := module() 
            ... 
    end module; 

     local A2 := module() 
             ... 
      end module; 

etc... 

end module

Now I can use the above with Grid. Below is work sheet to show this.
 

restart;

A := module()
    export main:=proc()
       print("i am in A:-main");
       B:-foo();
    end proc;

    export B :=module()
       export foo:=proc()
          print("in B:-foo()");
       end proc;
    end module;
end module:

kernelopts(opaquemodules=false): #see @acer code
S := subsindets({op(3,eval(A))}, `::`, (L)->convert(lhs(L),`global`)):
S := map(u->parse(cat("A:-",u)), eval(S,1));

{}

Grid:-Set(0, A:-main, op(eval(S,1)));
Grid:-Run(0, A:-main,[  ]);
Grid:-Wait();

"i am in A:-main"

Error, (in main) `%1` does not evaluate to a module

############ CHNAGE TO LOCAL, it works

restart;

 A := module()
    export main:=proc()
       print("i am in A:-main");
       B:-foo();
    end proc;

    local B :=module()
       export foo:=proc()
          print("in B:-foo()");
       end proc;
    end module;
end module:

kernelopts(opaquemodules=false): #see @acer code
S := subsindets({op(3,eval(A))}, `::`, (L)->convert(lhs(L),`global`)):
S := map(u->parse(cat("A:-",u)), eval(S,1));

{B}

Grid:-Set(0, A:-main, op(eval(S,1)));
Grid:-Run(0, A:-main,[  ]);
Grid:-Wait();

"i am in A:-main"

"in B:-foo()"

 


 

Download why_changing_to_local.mw

Too many problems to use Grid. But if this works, it is worth it, as it should be much faster than sequential.

Is there a way to fix that? 

 

try the maple export command and export to .ps, then convert .ps to pdf using ps2pdf command.

@acer 

Thanks, will try this and see if it works on my main setup.

@acer 

You are right. I had export there instead of local of the module variables. What I did only works if the variables have export on them.

I see now you used kernelopts(opaquemodules=false):  but this requires one to pass each individual variable name to be accessed if I want to keep the module variables local. I will try it and see.

the debugger ofcourse.

If Maple did not have a debugger, I would not even use Maple.

Even though the debugger is hard to use (line mode, no nice grapical interface like Matlab's debugger) it is for me indispensable. 

Too bad Maplesoft seems to have abandoned making any improvements to it any more.

 

Trace shows that `is/solve` fail, but could not find why.

Here is another strange result from coulditbe (cousin of is ?)

coulditbe(cos(x)=sqrt(1-sin(x)^2));

   #true

coulditbe(cos(x)=sqrt(1-sin(x)^2)) assuming x::real;

   #FAIL

@mmcdara 

I tend to use patmatch more. Main uses for me is to check if an ode has certain form to find what type it is.

I find pattern matching easier to use and more intuitive. After all, alot of math is about recognizing patterns and transformation.  But in Maple, pattern matching is somewhat more limited than it could be. But still, one can do alot with it.

@janhardo 

But the way you used `Or` is the same as using alternatives {  }

type(1+"s",`Or`(`&+`(integer,string),`&+`(string,integer) ) )

is same as

type(1+"s",{ `&+`(integer,string),`&+`(string,integer) } )

I was trying to use `Or` to tell type something like

type(1+"s", `&+`( `Or`(integer,string)))

Which ofcourse does not work. i.e. a way to avoid having to tell it the order.

So your `Or` at top level or using {} is same thing. One is forced to enumerate all possibles cases. 

With Pattern matching this is not needed.

@mmcdara 

          "stuff but it seems impossible to go further."

You could always step through the code in the debugger. You could open a text file on the side and using the debugger get the listing of each step or proc from the debugger, and stitch it into the text file you have open as you step through. Eventually, you can get all the code this way.

A := Statistics:-Sample('Beta'(3, 5), 10^5):
stopat(Statistics:-Mean);
Statistics:-Mean(A);

Here is some of the code processing the above

Statistics:-Mean:-ModuleApply:
   1*  try
       catch :
           ...
       end try

DBG> showstat

Statistics:-Mean:-ModuleApply := proc(X::{algebraic, {array, list, rtable, DataFrame, DataSeries}})
   1*! try
   2       return Quantities:-Dispatch('Statistics:-Mean',X,[NULL],_rest)
       catch :
   3       error
       end try
end proc

Statistics:-Quantities:-Dispatch := proc(qname::name, X::{algebraic, {array, list, rtable, DataFrame, DataSeries}}, parms::list)
   1 ! if type(X,'{array, list, rtable, DataFrame, DataSeries}') then
   2       return GetValueTab[':-DescriptiveStatistics'](qname,X,parms,_rest)
       else
   3       return GetValueTab[':-RandomVariables'](qname,X,parms,_rest)
       end if
end proc

Statistics:-Quantities:-Dispatch:
   2       return GetValueTab[':-DescriptiveStatistics'](qname,X,parms,_rest)

Statistics:-Quantities:-GetValueTab[DescriptiveStatistics] := proc(qname::name, X::{array, list, rtable, DataFrame, DataSeries}, parms::list, {matrixbycolumn::truefalse := true, weights::{array, list, rtable, DataFrame, DataSeries} := NULL})
local x, xx, w, ww, mbc_marker, answ;
   1   answ := Statistics:-DescriptiveStatistics:-CreateOutputRecord();
   2 ! if matrixbycolumn then
   3       mbc_marker := NULL
       else
   4       mbc_marker := 1
       end if;
   5   x, xx := PreProcessData(X,mbc_marker,':-reconstruct' = ':-summarize');
   6   if weights = NULL then
   7       Statistics:-DescriptiveStatistics:-GetValue(qname,[x, op(parms)],
             answ,_options['matrixbycolumn'],_rest)
       else
   8       w, ww := PreProcessData(weights,mbc_marker,':-reconstruct' = [':-
             summarize', xx]);
   9       Statistics:-DescriptiveStatistics:-GetValue(qname,[x, op(parms)],
             answ,_options['matrixbycolumn'],':-weights' = w,_rest)
       end if;
  10   return Statistics:-DescriptiveStatistics:-BuildOutput(answ,':-
         reconstruct' = xx)
end proc


Statistics:-Quantities:-GetValueTab[DescriptiveStatistics]:
   7       Statistics:-DescriptiveStatistics:-GetValue(qname,[x, op(parms)],
             answ,_options['matrixbycolumn'],_rest)



Statistics:-DescriptiveStatistics:-GetValue := proc(quantity::name, plist::list, answ::record, {matrixbycolumn::truefalse := true, weights::{array, list, rtable, DataFrame, DataSeries} := Vector(0)})
local columns, dtype, i, m, parms, rest, rows, weightsset, V;
   1 ! if type(weights,{array, list}) then
   2       weightsset := Vector(weights)
       else
   3       weightsset := weights
       end if;
   4   if type(plist[1],':-list'(':-Vector')) then
   5       parms := plist
       elif type(plist[1],{'array', 'list'}) then
   6       parms := subsop(1 = Array(plist[1]),plist)
       elif type(plist[1],':-rtable') and rtable_num_dims(plist[1]) = 2
         and matrixbycolumn then
   7       m := plist[1];
   8       rows := upperbound(m,1)-lowerbound(m,1)+1;
   9       columns := upperbound(m,2)-lowerbound(m,2)+1;
  10       rest := op(2 .. (NULL),plist), _rest, ':-weights' = weightsset;
  11       if convert(quantity,':-`global`') = ':-Mode' then
  12           dtype := NULL
           else
  13           dtype := ':-datatype = :-float'
           end if;
  14       answ:-value := Vector[':-row'](columns,dtype);
  15       if [rtable_options(m,':-storage',':-order')] = [':-rectangular
             ', ':-Fortran_order'] then
  16           for i to columns do
  17               V := ArrayTools:-Alias(m,(i-1)*rows,[rows]);
  18               answ:-value[i] := GetValueWorker(quantity,V,rest)
               end do
           else
  19           for i to columns do
  20               V := m[(NULL) .. (NULL),i-lowerbound(m,2)+1];
  21               answ:-value[i] := GetValueWorker(quantity,V,rest)
               end do
           end if;
  22       return
       else
  23       parms := plist
       end if;
  24   answ:-value := GetValueWorker(quantity,op(parms),_rest,':-weights' = 
         weightsset)
end proc

And so on...

It seems Statistics:-Mean is routed via some dispatch mechanism called Quantities:-Dispatch to the actual code of the implementation. Hard to see how to access and see that dispatch code.

interface(version);

`Standard Worksheet Interface, Maple 2024.2, Windows 10, October 29 2024 Build ID 1872373`

restart

showstat(Statistics:-Mean);


Statistics:-Mean := proc(X::{algebraic, {array, list, rtable, DataFrame, DataSeries}})
   1   try
   2       return Quantities:-Dispatch('Statistics:-Mean',X,[NULL],_rest)
       catch :
   3       error
       end try
end proc
 

 

print(Statistics)

module Statistics () description "a package for mathematical statistics and data analysis"; local DataManipulation, DataSmoothing, DescriptiveStatistics, Distributions, Estimation, Quantities, RandomVariables, Regression, Simulation, SummaryAndTabulation, Tests, Visualization, ExciseRepPts, ExciseRangeSearch, ExternalSupport, ParseRelative, PostProcessData, PreProcessData, ProcessDistribution, RealIntervals, Summarize, Warnings, Initialize, Terminate, PrintInfo, PrintRegressionInfo, CentralMomentDimensions, SplitDataPerm, AverageLeastSquares, doPredictiveLeastSquares; export _pexports, Distribution, RandomVariable, Specialize, MakeProcedure, AbsoluteDeviation, Bootstrap, CentralMoment, Cumulant, Decile, ExpectedValue, GeometricMean, HarmonicMean, HodgesLehmann, InterquartileRange, Kurtosis, Mean, MeanDeviation, Median, MedianDeviation, Mode, Moment, OrderStatistic, QuadraticMean, Percentile, Quantile, Quartile, RousseeuwCrouxQn, RousseeuwCrouxSn, Skewness, StandardDeviation, StandardError, StandardizedMoment, Variance, Variation, CDF, CGF, CharacteristicFunction, CumulantGeneratingFunction, CumulativeDistributionFunction, DiscreteValueMap, FailureRate, HazardRate, InverseSurvivalFunction, MillsRatio, MGF, MomentGeneratingFunction, PDF, Probability, ProbabilityDensityFunction, ProbabilityFunction, Support, SurvivalFunction, Correlation, CorrelationMatrix, Covariance, CovarianceMatrix, PCA, PrincipalComponentAnalysis, AutoCorrelation, CrossCorrelation, EvaluateToFloat, Count, CountMissing, CumulativeProduct, CumulativeSum, Detrend, Difference, Excise, Join, OrderByRank, Rank, Remove, RemoveInRange, RemoveNonNumeric, Scale, Select, SelectInRange, SelectNonNumeric, Shuffle, Sort, SplitByColumn, Tally, TallyInto, Trim, Winsorize, ExponentialSmoothing, KernelDensity, LinearFilter, MovingAverage, MovingMedian, MovingStatistic, WeightedMovingAverage, Range, TrimmedMean, WinsorizedMean, DataSummary, FivePointSummary, FrequencyTable, FisherInformation, Information, Likelihood, LikelihoodRatioStatistic, LogLikelihood, MaximumLikelihoodEstimate, MLE, Score, KernelDensitySample, Sample, InteractiveDataAnalysis, Fit, NonlinearFit, LinearFit, PolynomialFit, ExponentialFit, LeastTrimmedSquares, LogarithmicFit, Lowess, PowerFit, OneWayANOVA, PredictiveLeastSquares, RepeatedMedianEstimator, OneSampleZTest, OneSampleTTest, OneSampleChiSquareTest, TwoSampleZTest, TwoSampleTTest, TwoSamplePairedTTest, TwoSampleFTest, ShapiroWilkWTest, ChiSquareIndependenceTest, ChiSquareGoodnessOfFitTest, ChiSquareSuitableModelTest, AgglomeratedPlot, AreaChart, AutoCorrelationPlot, BarChart, Biplot, BoxPlot, BubblePlot, ColumnGraph, Correlogram, CumulativeSumChart, DensityPlot, ErrorPlot, FrequencyPlot, HeatMap, GridPlot, Histogram, KernelDensityPlot, LineChart, NormalPlot, ParetoChart, PieChart, PointPlot, ProbabilityPlot, ProfileLikelihood, ProfileLogLikelihood, RadarChart, QuantilePlot, ScatterPlot, ScatterPlot3D, ScreePlot, SunflowerPlot, SurfacePlot, SymmetryPlot, TreeMap, VennDiagram, ViolinPlot, WeibullPlot, FiniteNumericSupport, ListKnownDistributions, TaskTemplates; option package, load = Initialize, unload = Terminate, `Copyright (c) Maplesoft, a division of Waterloo Maple Inc. 2005`; end module

 

 

Download mean_print.mw

You can not integrate    z(x)*y'(x)  or z(x)*y''(x) if z(x) is not known.

How would you do this by hand? Even if you use integration by parts, since z'(x) is not known.

If you know what z(x) is, then it should be possible.

integrand:=diff(y(x),x$2)

diff(diff(y(x), x), x)

int(integrand,x)

diff(y(x), x)

integrand:=z(x)*diff(y(x),x$2);

z(x)*(diff(diff(y(x), x), x))

int(integrand,x)

int(z(x)*(diff(diff(y(x), x), x)), x)

IntegrationTools:-Parts(Int(integrand,x),z(x),diff(y(x),x$2))

z(x)*(diff(diff(y(x), x), x))-(Int((diff(z(x), x))*(diff(diff(y(x), x), x)), x))

 

 

Download int_feb_4_2025.mw

First 6 7 8 9 10 11 12 Last Page 8 of 90