Group Abstract Group Abstract

Message Boards Message Boards

29
|
114K 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 3 years ago
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
POSTED BY: Sander Huisman
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
POSTED BY: Neil Singer
POSTED BY: Aeyoss Antelope
POSTED BY: Benjamin Goodman
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

Sorting numerical data and the behavior of Sort

Mathematica has various ways of sorting data. Most commonly one wants to sort numbers. The command Sort can be used to do so:

Sort[{4, 2, 8, 1}]

returns:

{1, 2, 4, 8}

all very well. However, if one has symbolic answers, Sort might not do what you expect:

data3 = Sin[Range[10]]
data3 // N
Sort[data3]

gives:

{Sin[1],Sin[2],Sin[3],Sin[4],Sin[5]}
{0.841471,0.909297,0.14112,-0.756802,-0.958924}
{Sin[1],Sin[2],Sin[3],Sin[4],Sin[5]}

It looks like if Sort did not do anything! What is happening here? Well, Sort puts things in canonical order and decides whether they are ordered correctly using the default function Order (which works basically the same as OrderedQ):

OrderedQ[1,2]  (* True, they are ordered *)
OrderedQ[2,1]  (* False; they are not ordered *)
OrderedQ[Sin[2], Sin[3]]    (* True, they are ordered! *)

That might be a bit unexpected. Sort will only look at the structure, and then 2 comes before 3. If we want to explicitly sort by numerical value (rather than canonical order) one needs to specify this:

data3 = Sin[Range[5]]
data3 // N
Sort[data3, Less]  (* prior to V11.1 *)
N[%]
Sort[data3, NumericalOrder]   (* V11.1 and up *)
N[%]

One can do this in the above two ways (using NumericalOrder rather than Order) or using the function Less which will evaluate the number numerically and then compare them. Since Version 11.1 there is also a new function called NumericalSort which just does that:

data3 = Sin[Range[5]]
data3 // N
NumericalSort[data3]
N[%]

Now that we know why Sort sometimes gives unexpected results, and that we have found alternate ordering functions, we find that this is generally not fast.

data = RandomReal[1, 10^6];
AbsoluteTiming[Sort[data, Less];]

It takes several seconds (5.3 seconds on my laptop) to sort a million numbers! Ok, what's going on here? The problem is that Sort with a second argument does pair-wise comparisons, such that the algorithm scales very poorly. If the problem can be re-stated such that each element in a list gets a numerical value which can be sorted using the default ordering function (Order), then this is much faster. We can then improve the performance considerably by using SortBy and a second argument:

AbsoluteTiming[SortBy[data, N];]

or equivalently in this case (we already have approximate numbers so N is not necessary):

AbsoluteTiming[SortBy[data, Identity];]

which only takes 0.17 seconds on my laptop. Since we have approximate numbers, Sort itself works correctly and is fast as well:

AbsoluteTiming[Sort[data];]

Takes 0.16 seconds on my laptop.

Summary

  • If one only has pure numbers (1337, 1.337 et cetera) use Sort (or from version 11.1 on use NumericalSort).

  • If one has numbers but in some kind of symbolic form (Sin[3], Sqrt[5], Pi, E, Exp[2], 10 Degree, Quantity[Sqrt[..],...] or ...) use NumericalSort (or SortBy[... , N] for versions prior to 11.1).

  • If your problem is not one of those, then check if the problem can be recast in one where a single function gives a 'value' to each element that then can be sorted efficiently, if that is possible use SortBy with the correct second argument

Compare the following two examples:

SortBy[{"abc","ab","e","cd","efg"},StringLength]
Sort[{"abc","ab","e","cd","efg"},StringLength[#1]<=StringLength[#2]&]

Give the same result but the first one is generally much faster.

  • If such a rephrasing of the problem is not possible use the general Sort with appropriate ordering function.

Final words

Much more can be said about Sort (like the ordering of Sort for a mix of strings, symbols, and numbers). Feel free to comment on this post for additional things to consider when sorting...

POSTED BY: Sander Huisman

Learn how to use the Documentation Center effectively

Mathematica comes with the most comprehensive documentation I have ever seen in a software product. This documentation contains

  • reference pages for every Mathematica function
  • tutorials for various topics, which show you step by step how to achieve something
  • guide pages to give you an overview of functions about a specific topic
  • a categorised function navigator, to help you find appropriate guide pages and reference pages.
  • finally, the complete interactive Mathematica book

You can always open the Documentation Center by pressing F1. When the cursor (the I-beam) is anywhere near a function, then the help page of this function is opened. E.g. when your cursor is anywhere at the position where the dots are in .I.n.t.e.g.r.a.t.e., you will be directed to the help page of Integrate.

Reference pages:

A reference page is a help page which is dedicated to exactly one Mathematica function (or symbol). In the image below you see the reference page for the Sin function. Usually, some of the sections are open, but here I closed them so you see all parts at once.

enter image description here

  • In blue, you see the usage. It gives you instantly information about how many arguments the function expects. Often there is more than one usage. Additionally, a short description is given.
  • The Details section gives you further information about Options, behavioural details and things which are important to note. In general, this section is only important in a more advanced state.
  • In some cases, extra information is provided on the mathematical Background of the function explaining the depths of the method, its relation to other functions and its limitations (for example FindHamiltonianCycle).
  • The Examples section is the most important, because there you have a lot of examples, showing everything starting from simple use cases to very advanced things. Study this section carefully!
  • See Also gives you a list of functions which are related. Very helpful, when a function does not exactly what you want, because most probably you find help in the referenced pages.
  • Tutorials shows you tutorials which are related to the function. In the case of Sin it is e.g. the Elementary Transcendental Functions tutorial.
  • Related Guides gives you a list of related guide pages.
  • Related Links references to material in the web: Demonstrations, MathWorld pages, etc.

In general, my recommendation for viewing a help page is the following:

  1. Study the usage carefully
  2. Look up basic examples. If you don't find what you need, look up all examples
  3. Read the Details

And of course if you like the how-to style, you should read the referenced tutorials.

Guide pages:

Guide pages collect all functions which belong to a certain topic and they are an excellent resource when you try to find a function you do not know yet.

enter image description here

The guide page itself is often divided into several subsections collecting similar functions. In the image above, for instance, the Trigonometric Functions. Furthermore, you can find links to tutorials, etc. when you open the Learning Resources tab. At the end of each guide page, you will find references to related guide pages.

Final notes:

  • Since the complete documentation consists of usual Mathematica notebooks, all calculations and examples can be tested inside the help pages. Of course, you cannot destroy the documentation, because everything is reset when you close a help page.

  • You can always search the documentation by typing into the search bar on top of the Documentation Center:

    enter image description here

  • When coming from a different programming language, and you are not sure that a certain Mathematica function is equivalent to what you are used to, be sure to check the Properties & Relations section in the reference page to get ideas on what other functions could be relevant for your case.


Please find the original discussion here.

POSTED BY: Patrick Scheibe

Basic syntax of built-in functions

  • All built-in functions start from capital letters and are in CamelCase for compound names. Users of many other programming languages might miss this as they are used to different conventions. Examples: Plot, ListPlot, FindSpanningTree, etc.

  • Arguments of a function are inclosed in square brackets. Round parenthesis are used only for ordering of operations. Again, other languages use different conventions. Examples:

    • Cos[Pi] --- is a function with a single argument Pi.
    • BesselJ[1/2, 5] --- is a function with 2 arguments
    • (2-Cos[Pi])Sin[Pi/3] --- round parenthesis are used to order operations
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