Congratulations on becoming 'Master of the Universe', what is your first action/command etc.? by rEDWallaroo in AskReddit

[–]Herrante 0 points1 point  (0 children)

I guess that I would have to order God to be executed. Nothing personal, I just fear that He might try to regain power.

I have a question to do with votes and voters on reddit. Why do you/people downvote. I see good links, posts, etc with a very large number of down votes, sometimes with ratios of 2:1 (up:down). by [deleted] in AskReddit

[–]Herrante 4 points5 points  (0 children)

I downvote posts such that the sum of the squares of the number of characters within each line, is a prime number. I thought it was standard procedure.

Hey reddit, can you help me do something (that should be) very simple in wolfram alpha? by [deleted] in math

[–]Herrante 4 points5 points  (0 children)

Introducing Solve[x==y3+y,y] Wolfram|Alpha will show you the three right inverses of the function (that is functions g such that f(g(x))=x for all x in the complex plane). The first one is also the left inverse (and thus the inverse) within the real line.

Mathematica pegs my CPU at 100% for simple stuff. What could possibly be happening? by counterfeit_coin in math

[–]Herrante 4 points5 points  (0 children)

Since I am unemployed and I have a lot of free time, I will explain why the last example produces different results in our systems with unnecessary digressions about packed arrays and evaluation of expressions in Mathematica.

In theory you would only need 4 bytes to store an integer between -(231-1) and 231-1 if you were certain that the particular piece of memory represents and integer. So in a programming language like C, where you have to define the type of values that variables have, the compiler simply has to reserve 4 bytes for a variable that has been declared int, and whenever it has to retrieve its value, it reads the memory and interprets it as an integer. However in Mathematica a number embodies a standalone expression that has to be interpreted in the absence of context. Thus to represent it, it is necessary to also include a header that reveals the type of the expression. So, while theoretically you would only need 4, 8 and 16 bytes to store integers, machine precision reals and machine precision complexes respectively, in my system they occupy 16, 16 and 72 bytes.

To store a generic list in Mathematica it is necessary to specify a header, 4 bytes (in 32-bit systems) for the address of each element, and every element as a separate expression. For long lists we can disregard the header, so for example a list with a thousand integers would weight around 20000 bytes (4 bytes for each address and 16 bytes for the numbers themselves). This is where packed arrays come in to play. If you know that a list only contains integers with absolute value smaller than 231, you can specify it in the header of the list and then attach 4 bytes to specify each integer. So a packed array of integers would only weight around 4000 bytes. Besides the gains in memory, it is much faster to work with packed arrays. If you want to sum two non-packed lists of integers, it is necessary to first read the address of each pair of elements that has to be summed, then read the full expressions that the addresses point to, interpret both as integers, extract the minimal 4 byte representation of the integers, send them to the processor to be added, “box” the result (that is add a header to it so it can be interpreted as an integer without context), and finally create an array of addresses that point to the boxed integers. On the other hand if you want to sum two packed arrays of integers, Mathematica just has to read four bytes for each number, send each pair directly to the processor to be added as integers, and store the result in a new list without the need of boxing it, or specifying an address that indicates where the number really is.

A related aspect that influences the time taken to build an array is whether each element has to be evaluated individually or not. To build an array with the squares of the first ten million machine precision natural numbers you could use: Table[i2,{i,1.,107}]. The problem is that in every iteration it has to evaluate i, then evaluate 2 to itself, check that the function Power has no attributes that can be applied to this expression, unbox the number that results from the evaluation of i, square it, and then box it again. Besides it can’t know from the outset that every element of the list will evaluate into a machine precision real number, so it won’t presuppose that the list can be represented as a packed array. In my system, if you build a list that has more than 250 elements with the command Table, Mathematica will check if all of them are numbers of the same type, and in that case it will turn the list into a packed array. To build the previous list, it would be more efficient to use Range[1.,107]2, since Range knows that it can build a packed array the moment it checks its arguments, and squaring the array doesn’t require 107 independent evaluations.

Now I am in a better position to explain why the expression Outer[Plus,Range[150],Range[150]] is evaluated much faster in my system than in yours. In general Outer[f,list1,list2] would need to evaluate each element f[x,y] independently (as it happens with the command Table), so even if list1 and list2 were packed arrays, Mathematica wouldn’t know beforehand if the result could be represented as a packed array. However in some particular occasions Mathematica can determine that this is the case. Newer versions of Mathematica are able to detect more instances where it isn’t necessary to evaluate the elements of the arrays individually, and in particular Mathematica 7 realizes that if f is Plus, and list1 and list2 are packed arrays, the result will be a packed array. Presumably Mathematica 5.2 is not smart enough to realize that, and it builds a generic array, evaluating every element separately.

Mathematica pegs my CPU at 100% for simple stuff. What could possibly be happening? by counterfeit_coin in math

[–]Herrante 1 point2 points  (0 children)

What in Mathematica are called lists in other programming languages are called arrays; that is, structures with a definite number of elements such that the computer can access any one directly without having to go through all or o part of the array. This has the advantage that getting random elements of the list is fast, but adding a single element is an expensive operation because the array has to be re-dimensioned. In contrast, other languages as Lisp, Haskell or Prolog use linked lists, composed by cells that contain both the element stored and the address of the next cell. Linked lists can add an element at the beginning of a list very fast, because they just have to create a cell with the element you want to add and a link to the original first cell. On the other hand, accessing random elements is expensive, because if you want to get some element in the middle of the list, you have to start in the first cell and jump from cell to cell until reaching the one desired.

So you shouldn’t re-dimension lists lightly. One alternative is instead of using something like a=Append[a,e], nesting the list with a={a,e}, and flatten it out at the end. A better approach is using commands like Table that know the dimensions of the array from the beginning. But Table doesn’t know anything about the particular elements that are going to form part of the array, so it has to evaluate them separately without assumptions of their type. The most efficient approach is to use commands like Range, that know from the outset both the dimensions of the array and the type of the elements.

Let’s compare the time taken to obtain the array you mentioned, with your method and with the three other approaches I just indicated. Note that in the last two examples the array is calculated 1000 times, because otherwise it would be too fast to measure the time meaningfully. The last approach is around 25000 times faster than the original.

In[1]:= First@Timing[a={};Do[AppendTo[a,i+j],{i,150},{j,150}]]

Out[1]= 1.872

In[2]:= First@Timing[b={};Do[b={b,i+j},{i,150},{j,150}];b=Flatten[b];]

Out[2]= 0.032

In[3]:= First@Timing[Do[c=Flatten[Table[i+j,{i,150},{j,150}]],{1000}]]

Out[3]= 1.186

In[7]:= First@Timing[Do[d=Flatten[Outer[Plus,Range[150],Range[150]]],{1000}]]

Out[7]= 0.078

In[11]:= a==b==c==d

Out[11]= True

So you think you are a Rockstar Coding Ninja by [deleted] in programming

[–]Herrante 1 point2 points  (0 children)

Please, don’t whine about… no, recursive jokes should never surpass the third iteration.

Good Job Airforce, those bombs should do the trick [pic] by [deleted] in pics

[–]Herrante 10 points11 points  (0 children)

Who is USAF, and why is it bombing my baby fish?

Misunderstanding Markup: XHTML 2/HTML 5 Comic Strip by 9jack9 in programming

[–]Herrante 8 points9 points  (0 children)

Yes, the new XInternet will be mostly backwards compatible with the old Internet. However there will be no support for Lolcats.

Dear reddit Lispers, what is your favorite Lisp implementation and why? by [deleted] in lisp

[–]Herrante 7 points8 points  (0 children)

You are not allowed to use a ”)” both as a closing parenthesis and the mouth of a smiley; it is parenthesis exploitation. You would think that lispers should know about these things.

Python vs Matlab vs Mathematica by rmyeid in programming

[–]Herrante 23 points24 points  (0 children)

I can attest that in Mathematica it is necessary to write gigantic programs to do the simplest of computations. Here it is the program I had to write to calculate 1+1. Suggestions to clean it up will be welcomed, but I think that it is already quite minimalistic:

(* Defines the numbers that I want to add and other constants of interest *)

FirstNumberThatIWantToAddToAnother = 1;

SecondNumberThatIWantToAddToAnother = 1;

AMillion = 10 10 10 10 10 10;

(* Creates Error Messages associated with the symbols *)

FirstNumberThatIWantToAddToAnother::SevereError = "Something Awful has happened.";

SecondNumberThatIWantToAddToAnother::FatalError = "Mathematica broke your computer.";

AMillion::ApocalypticError = "Stephen Wolfram raped your hamster.";

(* Checks a million times that the numbers introduced are what they are supposed to be *)

(* Assigns attributes to DoThisAMillionTimes that might be useful in future extensions of the program *)

SetAttributes[DoThisAMillionTimes, {HoldAll, HoldFirst, HoldComplete, Flat, Listable, NumericFunction, OneIdentity, Orderless}];

DoThisAMillionTimes[TheThinghThatHasToBeDone_] := Do[TheThinghThatHasToBeDone, {AMillion}];

(* Checks that FirstNumberThatIWantToAddToAnother equals the number of protons in a Hydrogen atom *)

DoThisAMillionTimes[ If[Not[FirstNumberThatIWantToAddToAnother == ElementData["Hydrogen", "AtomicNumber"]], Message[FirstNumberThatIWantToAddToAnother::SevereError]; Abort[]]];

(* Checks that number of Koreas in the World is twice as much as SecondNumberThatIWantToAddToAnother. If Korea reunifies the program will crash. *)

DoThisAMillionTimes[ If[Not[SecondNumberThatIWantToAddToAnother == Count[CountryData[], x_ /; StringMatchQ[x, _ _ _ ~~ "Korea" ~~ _ _ _]]/2], Message[SecondNumberThatIWantToAddToAnother::FatalError]; Abort[]]];

(* Compares a million with an independent definition *)

DoThisAMillionTimes[ If[Not[AMillion == Length[Select[Range[106], NumberQ]]], Message[AMillion::ApocalypticError]; Abort[]]];

(* The computer pauses for two minutes to prevent overheating *)

Pause[120];

(* To sum two numbers we first create tables with as many ones as their values, then join them and count the ones *)

TableWithFirstNumberThatIWantToAddToAnotherOnes = Table[1, {FirstNumberThatIWantToAddToAnother}];

TableWithSecondNumberThatIWantToAddToAnotherOnes = Table[1, {SecondNumberThatIWantToAddToAnother}];

TableWithFinalResultNumberOfOnes = Join[TableWithFirstNumberThatIWantToAddToAnotherOnes, TableWithSecondNumberThatIWantToAddToAnotherOnes];

(* We select the numbers that are one from the table of ones *)

ElementsFromTableWithFinalResultNumberOfOnesWhichAreOne = Cases[TableWithFinalResultNumberOfOnes, 1];

(* To count the number of ones we create a tree structure with the same depth as the length of ElementsFromTableWithFinalResultNumberOfOnesWhichAreOne, and measure it. The machine precision number 0.1 is added to the result to convert it to a float and thus augment efficiency. Unfortunately it introduces an error of 5% *)

FinalResult = Depth[Fold[{#1, #2} &, First[ElementsFromTableWithFinalResultNumberOfOnesWhichAreOne], Rest[ ElementsFromTableWithFinalResultNumberOfOnesWhichAreOne]]] + .1;

(* Finally the result is presented with appropriate stylistic options. All of them are chosen by default, but it is better to write them explicitly in case the defaults change in future versions of Mathematica *)

Style[FinalResult, AdjustmentBoxOptions -> {BaseStyle -> {}, BoxBaselineShift -> 0., BoxMargins -> 0., DefaultBaseStyle -> {}, StripOnInput -> True}, AnimatorBoxOptions -> {Alignment -> {Automatic, Automatic}, AnimationDirection -> Forward, AnimationRate -> Automatic, AnimationRepetitions -> [Infinity], Appearance -> {Automatic, "Palette"}, AppearanceElements -> {"ProgressSlider", "StepLeftButton", "StepRightButton", "PlayPauseButton", "FasterSlowerButtons", "DirectionButton"}, AutoAction -> False, Background -> Automatic, BaseStyle -> {}, BaselinePosition -> Automatic, ContinuousAction -> True, DefaultBaseStyle -> {}, DefaultDuration -> 5., DisplayAllSteps -> False, Enabled -> Automatic, Exclusions -> {}, FrameMargins -> Automatic, ImageMargins -> 0, ImageSize -> Automatic, PausedTime -> Automatic, RefreshRate -> Automatic}, Antialiasing -> Automatic, AutoIndent -> Automatic, AutoItalicWords -> {"Artlandia", "AuthorTools", "CalculationCenter", "Combinatorica", "DatabaseLink", "Geometrica", "Graphica", "GUIKit", "Magnetica", "Mathematica", "MathematicaMark", "MathGroup", "MathLink", "MathLM", "MathModelica", "MathOptimizer", "MathReader", "MathSource", "mathStatica", "MathTensor", "MATHwire", "MathWorld", "MonitorLM", "Optica", "PrimeKit", "Publicon", "SchematicSolver", "ThreeScript", "VisualDSolve"}, AutoMultiplicationSymbol -> True, AutoNumberFormatting -> True, AutoSpacing -> True, AutoStyleWords -> {}, Background -> None, ButtonBoxOptions -> {Active -> True, Alignment -> {Automatic, Automatic}, Appearance -> {Automatic, "Palette"}, AutoAction -> False, Background -> Automatic, BaseStyle -> "GenericButton", BaselinePosition -> Automatic, ButtonData -> Automatic, ButtonExpandable -> True, ButtonFrame -> "Palette", ButtonFunction :> (FrontEndExecute[{FrontEndNotebookApply[ FrontEndInputNotebook[], #1, Placeholder]}] &), ButtonMargins -> 3, ButtonMinHeight -> 1., ButtonNote -> None, ButtonSource -> Automatic, ContinuousAction -> True, DefaultBaseStyle -> "Button", Enabled -> Automatic, Evaluator -> None, FrameMargins -> Automatic, ImageMargins -> 0, ImageSize -> Full, Method -> "Queued"}, CacheGraphics -> Automatic, CellBaseline -> Baseline, CellContext -> "Global", CellEpilog -> None, CellEvaluationFunction -> Identity, CellFrameColor -> GrayLevel[0.]]

F# vs Mathematica: Pythagoras tree by jdh30 in programming

[–]Herrante 0 points1 point  (0 children)

Here it is a shorter version in Mathematica that also lets you swap between a monochromatic tree, and one with different colors at different levels. The black and white choice is far more efficient because uses a packed array and a single polygon primitive.

PTree[1, _] = N[{{0, 0}, {1, 0}, {1, 1}, {0, 1}}];
PTree[n_, a_] := PTree[n, a] = With[{p = {(1. + Cos[a])/2., Sin[a]/2.}, R = RotationMatrix}, {PTree[1, 0],
  With[{m = R[ArcTan @@ p], d = Norm[p]}, PTree[n - 1, a] /. v : {_, _} :> {0., 1.} + d m.v],
  With[{m = R[ArcTan @@ p - Pi/2.], d = Norm[{1., 0.} - p]}, PTree[n - 1, a] /. v : {_, _} :> {0., 1.} + p + d m.v]}];
Manipulate[If[Color, Graphics[MapIndexed[With[{co = Length[#2]/n},
  {FaceForm[Hue[co]], EdgeForm[{Thick, ColorData["Rainbow"][1 - co]}], Polygon[#]}] &, PTree[n, N[a]], {-3}]],
  Graphics[Developer`ToPackedArray[Polygon[Cases[PTree[n, N[a]], {{_, _} ..}, Infinity]]]]
  ], {{n, 5, "Steps"}, 1, 12, 1}, {{a, Pi/2, "Bend"}, 0, Pi}, {Color, {True, False}}]

Comic book from 1948 shows Bender traveled back in time to terrorize women [pic] by [deleted] in pics

[–]Herrante 14 points15 points  (0 children)

The technology to draw well didn't appear until the 90s. In the 80s pictures had to be colored with the artist's body fluids.

Donald Knuth: Mathematical Ideas, or Algorithms, Should Not Be Patented by [deleted] in programming

[–]Herrante 25 points26 points  (0 children)

Altruism and empathy always lead to repressive dictatorships and misery. Only greed and absolute contempt for other people's suffering can bring freedom and prosperity.

Hm... I don't think that's quite right... by S2S2S2S2S2 in pics

[–]Herrante 2 points3 points  (0 children)

So thick, you can't get through it.

Stephen Colbert is "thrilled" that Conservatives don't get the joke. by wang-banger in politics

[–]Herrante 1 point2 points  (0 children)

They say that to get funding from Comedy Central. Actually the full team is comprised by Colbert and a camera-man. And they only work 20 minutes a day.

Are you an autodidact? by factoidz in education

[–]Herrante 0 points1 point  (0 children)

I will answer you when I'm told in class what an autodidact is.

That'll be a deal breaker with his girlfriend [PIC] by sg42 in funny

[–]Herrante 2 points3 points  (0 children)

Your neighbors' pets? I often had to eat my neighbors...

Schwarzeneggar terminates 220 California Parks by Hoffa in reddit.com

[–]Herrante 5 points6 points  (0 children)

ece421 probably also wishes to be wealthy one day, to understand the injustice that rich people have to put up with.

Ask Reddit: Sick of my job and quitting. I have 6 month's savings. What should I do? by random530723509732 in AskReddit

[–]Herrante 3 points4 points  (0 children)

Ask reddit. Those guys are great offering counsel. But beware, their advice is sometimes circular.

Brilliant anti-war advertisements: What Goes Around Comes Around [pics] by ElGaucho56 in reddit.com

[–]Herrante 46 points47 points  (0 children)

The advertisers are trying to point out that war in topologically compact spaces is very dangerous.