Message Boards Message Boards

0
|
3454 Views
|
5 Replies
|
2 Total Likes
View groups...
Share
Share this post:
GROUPS:

Replace[] does not compute 2nd element of the list

Posted 9 years ago
Replace[{{1, 2}, {3, 4}}, {x_, y_} -> {x, Log[2, y]}, 1]

has result

{{1, 1}, {3, Log[4]/Log[2]}}

Why does it not show 2 for the 4th number?

POSTED BY: steve ma
5 Replies

Before Mathematica used the rule, it evaluated the right hand side. Evaluating the rule by itself shows what happened:

In[60]:= {x_, y_} -> {x, Log[2, y]}

Out[60]= {x_, y_} -> {x, Log[y]/Log[2]}

The two argument form of Log evaluates to a ratio of natural logs unless both arguments are numeric. Then, when it substituted 4 for y, it preserved that form. Mathematica will not automatically recognize that it can simplfy the ratio of logarithms.

FullSimplify can simplify this. However, it's probably better to delay the evaluation. In this case, you could use RuleDelayed:

In[59]:= Replace[{{1, 2}, {3, 4}}, {x_, y_} :> {x, Log[2, y]}, 1]

Out[59]= {{1, 1}, {3, 2}}

Another way would be to define your own function for numeric arguments only:

In[56]:= log2[x_ /; NumberQ[x]] := Log[2, x]

In[58]:= Replace[{{1, 2}, {3, 4}}, {x_, y_} -> {x, log2[y]}, 1]

Out[58]= {{1, 1}, {3, 2}}
POSTED BY: John Doty

Hi,

try this:

Replace[{{1, 2}, {3, 4}}, {x_, y_} -> {x, N[Log[2, y]]}, 1]

Cheers,

M.

POSTED BY: Marco Thiel

Hi,

try this:

Replace[{{1, 2}, {3, 4}}, {x_, y_} -> {x, N[Log[2, y]]}, 1]

Cheers,

M.

POSTED BY: Marco Thiel
Posted 9 years ago

Thanks a lot. I added Round to get rid of the period.

POSTED BY: steve ma

The disadvantage of using N is that you get an approximate result, while Mathematica can do this exactly if given the chance.

POSTED BY: John Doty
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