Message Boards Message Boards

0
|
5123 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Why does this simple substitution (ReplaceAll) fail?

Posted 9 years ago

I am trying to calculate the product of some sines the arguments of which are stored in a list.

Product[Sin[aList[[i]]], {i, 1, Length[aList]}] /. aList -> {1, 1/2}

which outputs this indicating that Product is looping zero times, that is, apparently Length[aList] is evaluating to 0:

1

Similarly,

myList = {1, 1/2};
Product[Sin[aList[[i]]], {i, 1, Length[aList]}] /. aList -> myList

also outputs

1

But pasting myList directly into the line of code, like this

Product[Sin[myList[[i]]], {i, 1, Length[myList]}]

produces the desired result:

Sin[1/2] Sin[1]

What am I doing wrong?

POSTED BY: Jerry
2 Replies
Posted 9 years ago

Many thanks, Nasser, for your clear answer.

I’m obviously a bit of a noob with Mathematica which is maybe why I got confused. I think another explanation would be to render the desired result without the postfix notation, that is,

ReplaceAll[Product[Sin[aList[[i]]], {i, 1, Length[aList]}], aList -> {1, 1/2}]

which more clearly indicates that Length will be evaluated before ReplaceAll.

Oddly, (or not so oddly once you see the pattern with some of the Mathematica documentation), the ReplaceAll function syntax is not provided in the Mathtematica documentation, only the postfix /. .

POSTED BY: Jerry

You are doing the replacement outside of the product. By the time the product command is done its job, there is nothing to replace. Basically you are doing this:

Clear[aList];
sol = Product[Sin[aList[[i]]], {i, 1, Length[aList]}]

and now

 sol /. aList -> {1, 1/2}

But sol=1 so nothing gets replaced. Why not just do

 aList = {1, 1/2};
 sol = Product[Sin[aList[[i]]], {i, 1, Length[aList]}]

it is much simpler.

POSTED BY: Nasser M. Abbasi
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