Group Abstract Group Abstract

Message Boards Message Boards

29
|
115K Views
|
22 Replies
|
120 Total Likes
View groups...
Share
Share this post:

[CALL] Most common pitfalls for beginners of Wolfram Language

Wolfram Language (WL) is a powerful multi-paradigm programing language. There is a set of common mistakes that repeatedly tend to entrap new users. This is a call to describe such mistakes building a "black-listing" guide for novice coders. Please consider contributing. I suggest following simple rules (with gratitude adapted from a similar effort):

  • One topic per answer

  • Focus on non-advanced uses (it is intended to be useful for beginners and as a question closing reference)

  • Include a self explanatory title in header style (example: "# Basic built-in function syntax"; see syntax guide )

  • Explain the symptoms, the mechanism behind the scenes and all possible causes and solutions you can think of. Be sure to include a beginner's level explanation (and a more advance one too, if you can)

Please, use "Reply" to a specific comment for structured clarity of nested comments.


Table of Contents

POSTED BY: Vitaliy Kaurov
22 Replies
Posted 4 years ago

Keyboard combinations and keyboard mistakes. I'm a longtime Mathematica user but am surprised by the recent inadvertent results when trying to add comments to input. The second line below, the red square, is particularly problematic. It appears at the beginning of the input line and will change the properties of what is usually a variable and assignment operator (set). If it occurs with a variable that is subscripted, I have to reboot Mathematica; undo, Clear[], ClearAll[] will not fix whatever that red square does to my subscripted variables. The freeform input symbol shown is easy to search for (orange box with equals sign), but not so with the red box and other mistakes shown....

Wolfram Notebook

POSTED BY: Mark Bourland
Posted 4 years ago

Differences between "Equal" and "SameQ"


There are different ways of comparing two elements or more, the first one is less strict: using Equal (==); the second one, is more strict: using SameQ (===).

Let's take a look at the documentation page for Equal:

Equal Documentation Page

And now, the documentation page for SameQ...

SameQ Documentation Page

This alone doesn't tell much, but how exactly these two operators (== and ===) are different? The difference lies in their individual strictness.

If you want to compare numbers AND their types, use SameQ, if you want less strict comparisons, use Equal.

Equals vs SameQ

Sometimes, Equal outputs a symbolic equation, and that can be bad sometimes, if you want to ALWAYS output a boolean value, use SameQ.

Equal Symbolic vs SameQ Boolean

WARNING: SameQ has a higher precedence as an operator. If you want to replace values, replace the values while holding the operation.

SameQ precedes Equal

POSTED BY: Pedro Cabral

Don't perform operations on whole arrays by indexing individual elements....

Horrible:
output = ConstantArray[0, Length[data]]; 
For[j = 1, j <= Length[data], j++, output[[j]] = Sin[data[[j]]]];
output

Bad:
Table[Sin[data[[j]]], {j, 1, Length[data]}]

Nice:
Map[Sin, data]

And if the operation is Listable... Best: Sin[data]

POSTED BY: Jon McLoone

If i would get a euro for every time I see horrible/bad approach…

POSTED BY: Sander Huisman

Subscripted variables are a pain...use [i] indexing instead.

POSTED BY: Yaroslav Bulatov
Attachments:
POSTED BY: Raspi Rascal
Posted 8 years ago

Import and "CurrencyTokens"

Perhaps not 'common' but I was bitten by it twice until I made it 'my' default for data import. I assume for some legacy reason the stripping of currency symbols is the default behavior of the Import[] function. Seems an odd default behavior to me and worse the default behavior is not pointed out as boldly as I think it should be in the documentation.

Import[   , "CurrencyTokens" -> None]

Incorrect Import

Correct Import

POSTED BY: David Proffer

Numerical vs Symbolic -- What to do when plots are blank (and other strange errors)

The plotting functions require numerical inputs. This sounds obvious but most people have trouble debugging plots that come out empty. When something does not plot, the first thing to do is to evaluate the expression and look for undefined variables or typos.

Consider the following:

A = 12;
b = 3;
expr = a* b sin[theta];
Plot[expr, {theta, 0, 10}]

which yields a less than informative plot:

enter image description here

The best approach is to take the plot argument and evaluate it at a point somewhere in the plot range and see that it is numerical. It is often a good idea to evaluate it at the two extremes and the middle to make sure it is numerical everywhere.

expr /. theta -> 0
expr /. theta -> 5
expr /. theta -> 10

to get

 (* 3 a sin[0] 
3 a sin[5] 
3 a sin[10] *)

It becomes clear that the a is undefined and that sin does not evaluate (because of the lower case 's')

POSTED BY: Neil Singer

Case sensitivity and typos

I am far from a novice user, but I make a lot of typing mistakes, so case sensitivity catches me often...especially on properties and names in WDF, etc.

This command gets an error

ResourceData["On the origin of Species"]

This command gets the data

ResourceData["On the Origin of Species"]

This command gets an error...also I find the error message to be somewhat opaque

DateObject[{2016, 8, 4}, "week"]

This command evaluates the object

DateObject[{2016, 8, 4}, "Week"]
POSTED BY: Aeyoss Antelope
POSTED BY: Benjamin Goodman

Alternatives to Reap/Sow

1. I would like to mention Table[] in addition. In complicated situations, Reap and Sow maybe be a better alternative, but I've seen quite a bit of beginner's code that looks just like the Do-AppendTo loop above. In that particular case, Table[] is superior both in speed and legibility. It's about 20 times faster than the Reap version:

data = Table[RandomReal[x], {x, 0, 40000}];

(Asides: In some use cases, Map may be an even better choice. Also, many functions are "vectorized" or have special cases for efficiently constructing arrays; for instance, RandomReal[1, 40001] * Range[0., 40000.] produces nearly the same data 150 times faster than Reap, the maximum relative error being less than 10^-12 -- learning to think computationally in terms of arrays can speed up code significantly.)

2. Let me also add linked lists as an alternative (see also this answer by Leonid Shifrin). It is 5-10% faster than Reap & Sow.

data = {};
Do[data = {data, RandomReal[x]}, {x, 0, 40000}];
data = Flatten@data;

If the data is an multidimensional array, then we can structure the flattening operation by using a special head.

Block[{ll},    (* not necessary if  ll  is undefined *)
 data = ll[];
 Do[data = ll[data, RandomReal[x, 2]], {x, 0, 40000}];
 data = List @@ Flatten[data, Infinity, ll];
 ]

Example timing:

SeedRandom[0];    (* for reproducible randomness *)
data = Reap[Do[Sow[RandomReal[x, 2]], {x, 0, 40000}]][[2, 1]]; // AbsoluteTiming
(*  {0.097571, Null}  *)

SeedRandom[0];    (* for reproducible randomness *)
dataLL = ll[];
(Do[dataLL = ll[dataLL, RandomReal[x, 2]], {x, 0, 40000}]; 
   dataLL = List @@ Flatten[dataLL, Infinity, ll]); // AbsoluteTiming
(*  {0.08676, Null}  *)

data == dataLL
(*  True  *)
POSTED BY: Michael Rogers
POSTED BY: Sander Huisman

New in 12.2, ApplyTo x//=f

It's included on the Input Operator Forms webpage.

POSTED BY: Raspi Rascal

Thanks, had added a previous version of ApplyTo, now fixed, and also added [Application]. (https://reference.wolfram.com/language/ref/Application.html)

POSTED BY: Sander Huisman

see "x|->f — new syntax for Function with named variables"

btw your post is the only bookmark I am keeping from this community site.

POSTED BY: Raspi Rascal

Also added this explicitly. thanks!

POSTED BY: Sander Huisman

For some reason the following code is not working for me: ?5.5?=Missing["UnknownSymbol", "5.5?"] Has the floor function syntax been updated?

POSTED BY: Peter Burbery
Posted 4 years ago

Not sure how you are entering the left and right floor brackets but that is the problem,

\[LeftFloor]5.5\[RightFloor]
(* 5 *)

To enter from the keyboard esclfesc and escrfesc where esc is escape.

POSTED BY: Rohit Namjoshi

The forum screwed up some of the symbols and replaced them with ?. Now fixed.

POSTED BY: Sander Huisman
POSTED BY: Sander Huisman
POSTED BY: Patrick Scheibe
POSTED BY: Marina Shchitova
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard