I'm new to Mathematica. I have been going through the official reference and came across this article on rules to which I was led by a Google search on how to evaluate a expression, say x^2 + 5x - 4 for a certain value of x. And it worked quite well when I used:

x^2 + 5x - 4 /. x -> 5

But unfortunately, I didn't understand much of what happened when I typed that in. I got that by some trial-and-error with the help of the official reference. But I'd like to fully understand how to use it properly.

To sum up my current knowledge:

  • The rule is written in the form of lhs->rhs, as stated in the reference
  • It will not modify the actual value of x

I know that's ultra-vague. Hence, I'd like to know more about it. Precisely, my questions are:

  • What exactly is a rule? The reference states that a rule transforms lhs to rhs as in lhs->rhs. But that didn't make any sense to me :)
  • What exactly takes place when I type in the aforementioned code in Mathematica?
  • Where does the /. operator come into play? I've tried searching about it online but since it is an operator, i.e., made up of symbols, it's incredibly hard to do the same. As it is search engines love to ignore them.
  • Side-Request : I'd be glad if you educate me about other aspects I need to know to understand the answers to the above questions.

Finally, I'd like to mention that if this question has been answered before, I'd be glad to read the same, provided it does a good job of answering my questions as mentioned.

  • 5
    $\begingroup$ "I've tried searching about it online" - here's a tip: anytime you encounter an unfamiliar symbol or group of symbols in Mathematica, highlight it and press F1. $\endgroup$ – J. M.'s technical difficulties May 25 '16 at 16:50
  • $\begingroup$ @J.M. That was helpful.. Got the meaning of /. but still not sure about rules... $\endgroup$ – Fᴀʀʜᴀɴ Aɴᴀᴍ May 25 '16 at 17:05
  • 5
    $\begingroup$ I have discussed rules in my book, here. May be you will find that useful. $\endgroup$ – Leonid Shifrin May 25 '16 at 17:22
  • 1
    $\begingroup$ This PDF document contains an article that will very likely clear the whole mystery up for you. $\endgroup$ – m_goldberg May 25 '16 at 22:24

Re: "...what are its uses?"

eqn = Sqrt[x + 4] == x - 2;

soln = Solve[eqn, x, VerifySolutions -> False]

(*  {{x -> 0}, {x -> 5}}  *)

Results from Solve (also NSolve, DSolve, NDSolve, and others) are returned as Rules rather than setting the value of any variables. To verify solutions:

eqn /. soln

(*  {False, True}  *)

The first solution was an extraneous root. Mathematica excludes the extraneous root if VerifySolutions is True or you default to VerifySolutions->Automatic

soln2 = Solve[eqn, x]

(*  {{x -> 5}}  *)

eqn /. soln2

(*  {True}  *)
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.