# Tag Info

39

In Some Notes on Internal Implementation especially in Algebra and Calculus one finds interesting subtleties and differences between these two functions, e.g. The code for Solve and related functions is about 500 pages long. Reduce and related functions use about 350 pages of Mathematica code and 1400 pages of C code. There is much more than a ...

28

Internal`InheritedBlock (IIB) is similar to Block, except that it preserves the original definition of the function being passed to it. The function can then be modified as we wish inside the IIB without affecting the external definition. Let's see how Block works first: f[x_] := x Block[{f}, Print@DownValues[f]; f[x_, y_] := x y; ...

27

Since version 8, Solve and Reduce share a great deal of code. In fact, by Specifying Method -> Reduce in Solve, Solve will use Reduce behind the scenes to produce an answer. Off the top of my head, the key differences are as follows: 1) Reduce simplifies logical statements, while Solve solves equations. This means that given a logical statement ...

25

Not really a concise syntax, but you can also do this using Switch, which removes the need for writting the checking, and also allows patterns: fun[num_Integer] := Switch[num, 1, "Red", 2, "Orange", 3, "Yellow", _?PrimeQ, "Purple", _, "LightGray"] I used strings just to make the output nicer to verify the behavior. Naturally you would switch ...

23

For example you may do something like f[i_] := {Red,Orange,Yellow}[[i]] Edit You can easily add some robustness: f[l_List, i_Integer ] := l[[i]] /; 1 <= i <= Length@l; ll = {Red, Orange, Blue}; f[ll, 3]

21

Taking a limit depends on the path used to approach that limit. Consider the function in the question: f[x_, y_] := Piecewise[{{x y / (x^2 + y^2), x != 0 && y != 0}}, 0]; base = Plot3D[f[x, y], {x, -1, 1}, {y, -1, 1}, MeshStyle->Opacity[0.2], PlotStyle->Opacity[0.5]] (A plot of its graph, saved here as base, appears in subsequent figures.) ...

20

Head can return any head. There is no predefined list. expr = myArbitraryHead[1, 2, 3]; Head[expr] myArbitraryHead A head does not even need to be a Symbol: expr2 = (2 Pi)[x, y, z]; Head[expr2] 2 π Most heads are shown explicitly in the FullForm of the expression: FullForm[{"a" + "b", 1/3}] Head /@ {"a" + "b", 1/3} List[Plus["a", "b"], ...

19

Intro I will treat your question in a somewhat broader context of parameter-passing semantics in Mathematica in general. Many points of confusion here come from analogies and comparisons with more traditional languages, and it is important to realize that Mathematica uses entirely different (from most other languages) mechanisms for parameter-passing. ...

19

Answer: Fixed in 9.0.1. 9.0.1 is a free upgrade for registered 9.0.0 users, and is available for download from the Wolfram User Portal. Explanation as to why/how it was busted. This is not something I would typically post at all. Not because I'm afraid to show how the sausage is made (for those who have the stomach), but more because it seems off-topic ...

18

Scoping constructs, lexical scoping and variable renamings It pays off to understand a bit deeper how the scoping constructs work and what happens behind the scenes when you execute one. In addition to the documentation, this was discussed in part here, but let us present some summary. When the lexical scoping construct Sc[vars, body] executes (where Sc ...

17

Not sure if this will work for you, but... There is a cool blog by Roman Osipov in Russian (use Google Translate to translate): Study of arbitrary functions by methods of mathematical analysis in the system Mathematica I will give 2 functions from there (see the blog for more tricks). The domain of the function DefinitionDomain[expr_, variable_: x] := ...

16

Best place is to make a package. But if you do not feel like it, you can put the definitions in the init.m file using init.m see http://reference.wolfram.com/mathematica/ref/file/init.m.html for more information on using init.m. From the above: "Possible locations for init.m files include the following:" $BaseDirectory/Kernel kernel initialization code ... 16 There was an update for Array, not done to the end. The method below does not work for earlier versions even though that Array is New in 1 | Last modified in 4 Moreover WRI forgot to update docs for error messages: Array::plen - the first example gives no error in V9. V9 Array[# &, n, {start, stop}] Array[# &, 10, {-1, 1}] {-1, ... 15 Preamble This is IMO a very good question. I will try to describe an approach based on code-generation, which in my view would allow one to get the most benefits of declarative rule-based-like definitions without essentially imposing eny limitations or introducing any inconsistencies. The resulting functions can also be Compiled. General solution via code ... 15 Have a look at this; http://reference.wolfram.com/mathematica/guide/MathLinkCLanguageFunctions.html I haven't used it in C/C++ but it works fine in C# and Java. Basically you create a connection to a Mathematica kernel and then pass it native data types. Works nicely. Here is some sample code in Java that I used when I first did this; import ... 15 The best I have is manual RHS holding and Join, after which an arbitrary head could be Applied: Join @@ Cases[expr, x : _Times :> Hold[x], 3] Hold[2/2, 8/4, 1/0] This could be done automatically as follows: makeHeld[(L_ -> R_) | (L_ :> R_)] := L :> HoldComplete[R]; makeHeld[pat_] := x : pat :> HoldComplete[x]; heldCases[expr_, rule_, ... 14 This is a matter of rules ordering for CountryData definitions. You have to do something like this: Unprotect[CountryData]; CountryData[c_String, "MyProperty"] := 0; (*actually call to another function*) DownValues[CountryData] = RotateRight[DownValues[CountryData]]; Protect[CountryData]; This reorders the definitions so that yours is at the top (or close ... 14 Use a dispatch table. It is an optimized element -> value lookup table that can be used to replace an element any time with its value. Now it does matching-and-finding every time, but if your list is not too big, this is pretty fast. dispatch = Dispatch[Thread[elements -> chemistry]]; ratio[elemA_, elemB_, disp_] := (elemA/elemB) /. disp; ratio[elemA_, ... 13 As you say, this is a straightforward application of Fold, which is also perhaps the cleanest solution you can get. I'm guessing that you're seeking Table based approaches since you didn't want to deal with having to "fold properly". I'll complete the Fold application here so that you can see how it is applied: n = {n1, n2, n3, n4, n5}; d = {d1, d2, d3, d4, ... 13 Simple version using a variant of memoization While part of the answer I was going to give was already posted by Istvan, I will still post mine since the self-precomputing part was not part of Istvan's answer. The following will use the variant of memoization to precompute the dispatch table: ClearAll[elem]; elem[chem_, element_] := With[{dispatchTable = ... 13 Accumulate is absolutely the most idiomatic and appropriate answer here. However since Mathematica is very powerful at list manipulation, it might be illustrative to show you couple of other ways of doing the same thing, just so you learn to think outside of mainstream procedural ways. 1. Using FoldList: This is a functional way of doing exactly what you ... 13 The code for the default ComplexityFunction was posted on MathSource a number of years ago by Adam Strzebonski (of Wolfram Research). You will see reference to the original reply from Adam referenced in a MathGroup reply from Andrzej Kozlowski dated 12 Jan 2010 with the subject: "[mg106386] Re : Radicals simplify". I mention all that because I can't get the ... 12 One simple solution is: fun[1] = Red; fun[2] = Orange; fun[3] = Yellow; A more complex solution that accepts arbitrary equivalence lists at run time: fun[{ins_, outs_}] := Function[x, Piecewise[MapThread[{#2, x == #1} &, {ins, outs}], x]]; f = fun[{{1, 2, 3}, {Red, Orange, Yellow}}]; f[2] RGBColor[1, 0.5, 0] 12 You could use ReplaceAll to write your function this way: fun[num_Integer] := num /. {1 -> Red, 2 -> Orange, 3 -> Yellow} This also allows pattern matching, and works better than switch in case you want to name parts of your pattern: findpeople[dbconn_, name_] := DBSelect[dbconn, "People", name] /. {$Failed :> (Message[findpeople::conn]; ...

12

Well, the smartass answer would be ContinuedFraction[E - 2, n] So your approximation function (if I understood correctly) would be FromContinuedFraction[ContinuedFraction[E - 2, n]] But the way I would generate this particular sequence manually is something along these lines: ls[n_] := Module[{s}, s = 2 Range[n]; {1, Riffle[s, {{1, ...

12

I know two approaches to this: In[1]:= FullSimplify[SeriesCoefficient[ArcTan[y], {y, x, n}] n!, Element[n, Integers] && n > 0] Out[1]= 1/2 I ((-I - x)^n - (I - x)^n) (1 + x^2)^-n Gamma[n] and In[2]:= FullSimplify[InverseFourierTransform[(-I k)^n FourierTransform[ ArcTan[x], x, k] , k, x], Element[n, Integers] && n > 0] ...

12

You need partitioning, Partition and parameters: 2 for pairs, 1 for unit overhang/offset, and then averaging each pair, using Map, short-notated /@. Partition[{a, b, c, d}, 2, 1] {{a, b}, {b, c}, {c, d}} These will all make the averages: Mean /@ Partition[N@badSource, 2, 1] MovingAverage[N@badSource, 2] ListConvolve[{{.5}, {.5}}, badSource] ...

12

\$Post is handy but it can get confusing when you want to use it for many things at once. I propose using MakeBoxes for this kind of thing as it is specifically intended for specifying formatted (Box) output. Interpretation is used to make the output work correctly as input. The right-hand-side of the definition can be either explicit *Box expressions or ...

12

The question made me wonder about zero-order interpolations. It's hardly clear which is the right way. When I tried to figure out why ListLinePlot would use a different Interpolation, I noticed it didn't seem to use an Interpolation for orders 0 or 1 at all, but did it the simple way which you might use by hand: connect the dots. This was probably done ...

12

There are nice trigonometric formulas δ = 0.01; trg[x_] := 1 - 2 ArcCos[(1 - δ) Sin[2 π x]]/π; sqr[x_] := 2 ArcTan[Sin[2 π x]/δ]/π; swt[x_] := (1 + trg[(2 x - 1)/4] sqr[x/2])/2; Plot[{TriangleWave[x], trg[x]}, {x, -2, 2}, PlotRange -> All] Plot[{SquareWave[x], sqr[x]}, {x, -2, 2}, PlotRange -> All, Exclusions -> None] Plot[{SawtoothWave[x], ...

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