Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy do Replace and ReplaceAll give different results even when only one rule and one expression is used?
    primarykey
    data
    text
    <p>Maybe someone can explain to me why <code>Replace</code> gives a different answer than <code>ReplaceAll</code>, even though I am using one rule, and, I think, I have one expression.</p> <p>According to the documentation:</p> <pre><code>ReplaceAll looks at each part of expr, tries all the rules on it, and then goes on to the next part of expr. The first rule that applies to a particular part is used; no further rules are tried on that part, or on any of its subparts </code></pre> <p>and for Replace</p> <pre><code>A list of rules can be given. The rules are tried in order. The result of the first one that applies is returned. If none of the rules apply, the original expr is returned. </code></pre> <p>I have this expression:</p> <pre><code>z/(0.5 -1.4 z+z^2) </code></pre> <p>and this one rule</p> <pre><code>z -&gt; Exp[I*w] </code></pre> <p>The following input</p> <pre><code>Clear[z] hz = z/(0.5 - 1.4 z + z^2); Replace[hz, z -&gt; Exp[I*w]] ReplaceAll[hz, z -&gt; Exp[I*w]] </code></pre> <p>yields this result:</p> <pre><code>z/(0.5 -1.4 z+z^2) (*from Replace*) E^(I w)/(0.5 -1.4 E^(I w)+E^(2 I w)) (*from ReplaceAll*) </code></pre> <p>So, <code>ReplaceAll</code> did the job I expected, but not <code>Replace</code>. The only thing I think I am missing here, is what makes Parts of an expression. So maybe hz is not 'one' expression? Ok, fine, but it should then have been able to apply the rule at least to one part of it. But it did not do any replacement anywhere</p> <pre><code>FullForm[hz] Times[z,Power[Plus[0.5`,Times[-1.4`,z],Power[z,2]],-1]] </code></pre> <p>Isn't hz one expression? If not, how many parts does it have? Is it the number of leaves at the end of the graph generated by <code>TreeForm[hz]</code>? If so, then I see 3 'z' in there, and <code>Replace[]</code> should then have replaced one of them</p> <p><img src="https://i.stack.imgur.com/PCS24.png" alt="enter image description here"></p> <p>I always used <code>/.</code> without thinking about it, which is the same as <code>ReplaceAll</code>, but now I used <code>Replace[]</code> thinking is was the same as <code>/.</code>, I found this and noticed the different functions. (so many functions to learn, so little time :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload