Tag Info

Hot answers tagged

64

What this answer is and is not To avoid some confusion and misunderstanding, let me state right away what is the intended status of this answer. This answer is not A tutorial to the subject A systematic, or complete, introduction to the subject An authoritative answer putting the final word on the subject This answer hopefully is An (subjective!) ...


20

Use pure functions (Function) and "InlineExternalDefinitions" -> True: g = #^2 &; f = # + 1 &; compiledFunction = Compile[{{x, _Real, 0}}, f@g[x], CompilationOptions -> {"InlineExternalDefinitions" -> True}]; CompilePrint[compiledFunction] 1 argument 1 Integer register 4 Real registers Underflow ...


17

That's an interesting first question. Welcome. :-) From a simplistic perspective this should work, but as you observe there are evaluation properties that are more complex. Here is a reference for most (but not all) behavior: The Standard Evaluation Sequence Let's follow those steps for your example. Heads are evaluated first Evaluate the head h of ...


16

Implementation The following implementation is based on expression serialization and SequenceAlignment built-in function. The idea is to break expressions into constituent parts, then align these part sequences, and then determine the positions where the expressions are different. The auxiliary heads we will need are inert heads diff and myHold, the latter ...


16

This is a tricky case indeed, because what you basically ask for is compile-time evaluation (macro-style). Generally, the answer is to use meta-programming, to assemble the compiled expression at run-time. The reason your attempt did not work is that the expression you want to evaluate is too deep for Evaluate to be effective. Solution using in-place ...


14

Ok, what you have here is some classic example of what is called "Evaluation leaks". So, first, the corrected code: ClearAll[capture] SetAttributes[capture, HoldAllComplete]; capture[expr_ /; AtomQ[Unevaluated[expr]]] := {Head[Unevaluated[expr]], expr}; capture[head_[args___]] := {head, capture /@ Unevaluated[{args}]}; Now, you can inspect it and ...


12

Here I offer the safe version of Get that can be used successively to collect all the source files and contexts of packages without polluting the memory (too much). What it does I have practically reverse-engineered all the necessary functions (Get, Needs, BeginPackage, Begin, EndPackage and End) so that I could inject the monitoring code for ...


7

Not an answer per se, but two clarifications (which are too long for the comment box): 1) The Wiki definition you have linked to for a narcissistic number is not really apt. The Wiki page is actually describing the definition for an Armstrong Number, also known as pluperfect digital invariants, or m-narcissistic numbers, such as: $$407 = 4^3 + 0^3 + 7^3$$ ...


7

Here is a functional approach: Narciss[x_] := With[{num = IntegerDigits[x]}, Total[num^Length[num]] == x] Here is a compiled version of the above function: NarcissC = Compile[{{x, _Integer}}, With[{num = IntegerDigits[x]}, Total[num^Length[num]] == x], Parallelization -> True, CompilationTarget -> "C", RuntimeAttributes -> Listable, ...


6

I'm not sure what you're trying to do here and most probably Nasser's admonition rings true, but perhaps you want something like this?: Do[ CellPrint @ Cell[BoxData[RowBox[{RowBox[{"r", "[", i, "]"}], "="}]], "Input"], {i, 5} ] Alternatively you might make use of \[Placeholder] and Defer: Do[CellPrint @ ExpressionCell[Defer[r[#] = \[Placeholder]], ...


6

If you can convert expressions to text form, there's a possible answer here. I sometimes use it to compare notebooks: notebook1 = StringJoin[ Import["/tmp/freaky-illusion.nb", "Plaintext"]]; notebook2 = StringJoin[ Import["/tmp/freaky-illusion-1.nb", "Plaintext"]]; System`Dump`showStringDiff[notebook1, notebook2]


6

Evaluate will solve this. F[x_] := x + 2; G[x_] := x; ff = Compile[{x}, Evaluate@F[G[x]]]; <<CompiledFunctionTools` CompilePrint@ff result 1 argument 1 Integer register 2 Real registers Underflow checking off Overflow checking off Integer overflow checking on RuntimeAttributes -> {} ...


5

Please be gentle with me - this is my first ever post to stackexchange. Firstly, I'd like to say that I found Faysal's post both fascinating and outstandingly useful (I would upvote it if I could, but I have insufficient reputation). It introduces techniques I'm sure I shall use a great deal. However, it doesn't, quite, cater for all use cases. Where a ...


4

From a cold start, I would have written it like this: findNarc = Compile[{{stop, _Integer}, {pow, _Integer}}, Do[ If[Total[IntegerDigits[n]^pow] == n, Sow[n]] , {n, 1, stop} ] , RuntimeOptions -> "Speed", CompilationTarget -> "C"]; However, it is slower than your function (which takes 0.326 seconds on my machine) ...


4

Following belisarius comment you could do something like Function[z, z = f /@ z, HoldFirst]@{x, y} So you put the Map operation inside the pure function. E.g. x = {1, 2, 3}; y = {4, 5, 6}; f = #1 + 1 &; Function[z, z = f /@ z, HoldFirst][{x, y}]; x y seems to work.


4

I'm not to present any thorough analysis if metaprogramming is viable, but I could give a hint towards this issue. I don't think there is any fundamental barrier for metaprogramming in Mathematica, but I doubt we could develop this way anything really powerful. To point out a practical obstacle (though by any means not a no-go theorem) I suggest to take a ...


4

Other solutions: f2 = "Compile[{{arr,_Real,2}}, Module[{a,b,c,d},{a,b,c,d}=arr;" <> ToString[ InputForm@ Map[Mean, Partition[Tuples[{a, b, c, d}, 2], 4], {2}]] <> "],RuntimeAttributes->{Listable}]" // ToExpression; f3 = Compile[{{arr, _Real, 2}}, Module[{a, b, c, d}, {a, b, c, d} = arr; #], ...


4

I'm guessing the OP is looking a way to generate a number of indexed assignments from a list of data elements. If so, then maybe something like the following will work for the OP: Clear[data, r]; data = RandomInteger[{0, 99}, 5]; MapIndexed[(r[#2[[1]]] = #) &, data]; ?r Global`r r[1]=14 r[2]=95 r[3]=39 r[4]=26 r[5]=60


3

For diff'ing code fragments/expressions, you can copy-and-paste as "Plain Text" into Quick Diff (online) or into WinMerge (PC-based), ref. http://stackoverflow.com/q/15655828/879601 (also mentions a Mac-based method using Bash). E.g. WinMerge:- (For diff'ing packages and notebooks I favour CSDiff.)


3

Well, one obvious idea would be to build on the struct implementation by Bob Beretta. You would have to add information about methods and modify the implementation of --> to consider those as well, and for polymorphism, you'd also have to store the base class (or base classes, if multiple inheritance should be supported), and have --> look there if the ...


3

A very useful idiom for avoiding evaluation leaks is: foo= Function[{expr, pattn, levels}, Extract[Unevaluated[expr], Position[Unevaluated[expr], pattn, levels], HoldComplete], {HoldAllComplete}] This function foo finds parts of expr at specified levels that match pattn and most important it wraps them in HoldComplete before they get a chance to ...


3

Dynamically generated Do loops:) cnar = With[{n = 7}, With[{var = Array[Unique["x"] &, n]}, With[{n1 = FromDigits@var, n2 = Total[var^n]}, Compile[{Null}, Do[If[n1 == n2, Sow@n1], ##], RuntimeOptions -> "Speed", CompilationTarget -> "C" ] & @@ MapAt[1 &, Thread[{var, 0, 9}], {1, 2}] ] ] ]; ...


3

nar[m_] := ToExpression[ "Compile[{$},Do[With[{n=0" <> StringJoin[ Table["+1" <> Array["0" &, m - 1 - i, 1, StringJoin] <> "a" <> ToString[m - 1 - i], {i, 0, m - 1}]] <> ",n2=0" <> Table["+a" <> ToString[m - 1 - i] <> "^" <> ToString[m], {i, 0, m - 1}] <> ...


2

This is not a complete answer, but here I will suggest a somewhat different way to extract the dependencies, than in Istvan's answer. I think my method is somewhat more economical. The idea is to load the package of interest in a dynamic environment where $Packages variable is reset to {} initially. This will automatically prompt all packages to be loaded ...


2

As mentioned in my comment, it is possible for the example you have shown to achieve the same thing without a recursion and without even restarting NDSolve. The trick is to introduce a discrete variable which is changed at each event. Here is something that I think does the same thing as your code: cVals = {1, 2, 3}; tstart = 0; xsol = Quiet[NDSolveValue[{ ...


2

Here is a simplistic approach, I'd be interested in how it does or does not meet your requirements: r={1,2,3,4,5,6,7}; {r[[1]],r[[5]],r[[2]]} {1, 5, 2} If you wanted a more structured input format, try setting the value of r equal to the result of the first part of an input table (via menus, Insert->Table/Matrix->New ) which gives you something ...



Only top voted, non community-wiki answers of a minimum length are eligible