Message Boards Message Boards

GROUPS:

User-defined assignment is ignored in large Table[ ] computation

Posted 2 months ago
420 Views
|
3 Replies
|
0 Total Likes
|

I observed a strange behavior when I create a definition for a build-in function like Abs[]. If I use them e.g. in Table, the user definition is ignored when the table becomes large. Here is the example to illustrate this phenomena:

Unprotect[Abs]
Abs[x_] := x^2

Small table:

Table[Abs[i], {i, 30}]

{1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900}

Larger table:

Table[Abs[i], {i, 300}]

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, <<277>>, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300}

I use Mathematica 10.0.2 (x64) on Windows 10

3 Replies
Posted 2 months ago

That is certainly a much safer operation because the definition is associated with f, not Abs. For more details take a look at this and this.

Posted 2 months ago

Thanks for your reply. There is no real problem to be solved, I just want to understand the internals of Mathematica.

So, overwriting a function do not guarantee the replacement at all kind of situations.

What about using UpSetDelayed?

Abs[f[x_]] ^:= x^2
Table[Abs[f[i]], {i, 30}]
Posted 2 months ago

Hi Martin

Compare

Table[Abs[i], {i, 249}] // Trace
Table[Abs[i], {i, 250}] // Trace

When the upper bound exceeds 249 Table probably uses a version of Abs that is internal and optimized for long lists.

Lesson: Modifying built-in functions is risky and unpredictable.

What problem are you trying to solve? Perhaps there is a better solution for it rather than this example.

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract