# Formatting expressions with numeric exponents using pattern matching

Thank you all in advance.

Question: I want to change the format of this expression (n + r)^3/n^3 into this (1+r/n)^3using rules an patterns.

I manage to work this with symbolic exponents. In this example q:

(n + r)^q/n^q /. (n + r)^q_/n^q_ -> HoldForm[(1 + r/n)^q](*This works with symbolic exp*)


But if I change exponent q for any number, it won't work any longer.

(n + r)^3/n^3 /. (n + r)^q_/n^q_ -> HoldForm[(1 + r/n)^q] (*This does not work with numeric exp*)


## 1 Answer

Try the following:

expr1 = (n + r)^q/n^q
r1 = (n_ + r_)^q_  -> n^q (1 + r/n)^q
expr2 = expr1 /. r1


$$\left(\frac{r}{n}+1\right)^q$$

(n + r)^3/n^3 /. r1


$$\left(\frac{r}{n}+1\right)^3$$

• Thank you Syed. Your method works. I am studying it. But, why doesn't the substitution I tried work with numbers? Nov 19 '21 at 0:11
• why doesn't the substitution I tried work with numbers? because Mathematica automatically modify/simplify the expression when q is a number vs. symbol. See the difference printed after writing (n+r)^q/n^q and then q=3; (n+r)^q/n^q. Do you know see why? Look at the FullForm of each also to see the difference. Nov 19 '21 at 2:46
• @Sanmuten : Nasser has already described why. Another way of thinking about it is that if you are asking Mma to expand (a+b)^n. How can it do so, if n is not an integer? As soon as you provide it n=3, it simplifies and gets to cancel the denominator.
– Syed
Nov 19 '21 at 7:05