0
|
3246 Views
|
5 Replies
|
2 Total Likes
View groups...
Share
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/Log}}  Why does it not show 2 for the 4th number?
5 Replies
Sort By:
Posted 9 years ago
 Before Mathematica used the rule, it evaluated the right hand side. Evaluating the rule by itself shows what happened: In:= {x_, y_} -> {x, Log[2, y]} Out= {x_, y_} -> {x, Log[y]/Log} 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:= Replace[{{1, 2}, {3, 4}}, {x_, y_} :> {x, Log[2, y]}, 1] Out= {{1, 1}, {3, 2}} Another way would be to define your own function for numeric arguments only: In:= log2[x_ /; NumberQ[x]] := Log[2, x] In:= Replace[{{1, 2}, {3, 4}}, {x_, y_} -> {x, log2[y]}, 1] Out= {{1, 1}, {3, 2}} 
Posted 9 years ago
 Thanks a lot. I added Round to get rid of the period.
Posted 9 years ago
 Hi,try this: Replace[{{1, 2}, {3, 4}}, {x_, y_} -> {x, N[Log[2, y]]}, 1] Cheers,M.
Posted 9 years ago
 The disadvantage of using N is that you get an approximate result, while Mathematica can do this exactly if given the chance.
Posted 9 years ago
 Hi,try this: Replace[{{1, 2}, {3, 4}}, {x_, y_} -> {x, N[Log[2, y]]}, 1] Cheers,M.