# Should Expanding a function result in changes to its Plot?

(Title needs improving)

I'm trying to find the analytical expression for the attenuation of an AC voltage through a passive low-pass filter. The solution involves finding the time-dependent charge (q[t]) for the circuit and then calculating the voltage drop across the capacitor (q[t]/c). The equation is easy enough to solve (by Mathematica, not me).

Clear[q]
q[t_] := Evaluate[q[t] /. First@
DSolve[{v Sin[2 Pi f t] - q'[t] r - q[t]/c == 0, q == 0},
q[t], t]]
fp = {v -> 1, f -> 40., r -> 10000, c -> 10^-6};


The rules fp are example variables for the input voltage, frequency, resistance and capacitance. Plotting the solution, we find something odd at long times.

Plot[q[t]/c /. fp, {t, 0, 10}] ...which goes away if we Expand:

Plot[Expand[q[t]]/c /. fp, {t, 0, 10}] Comparing the "original" and expanded forms of the expression, we see that Mathematica is dealing with multiplying very large and small exponentials which, upon inspection, should cancel out.

q[t]/c
Expand[q[t]/c] Is this behavior a bug or is it inherent to math on a finite-precision device and therefore the user must be aware of the potential pitfall?

To solve my problem, I am actually interested in the amplitude of the resulting signal, which we can obtain from the coefficients of the sin and cos terms. Is there a convenient way to obtain these values? Right now, what I'm doing is a bit clumsy (but works).

Rest@Level[Expand[q[t]/c], {1}] /. {Cos[_] :> 1, Sin[_] :> 1}
Simplify[Sqrt@Total[#^2 & /@ %]/v, v > 0] It does not appear that there is a built in method for obtaining coefficients from a user defined series (e.g. CustomCoefficients[<expr>, <pattern>])

• One of the first things I do is replace Plot by Table: Try Table[q[t]/c /. fp, {t, 0., 10.}] -- important: Use machine precision in Table. Oct 15 at 19:41
• @MichaelE2 That does reveal the problem right away. Oct 15 at 22:28
• Just generally, on the title, and your suspicions about numerical precision, the answer is yes - differently expanded forms of the same expression can lead to better or worse precision. There are tools to find more accurate floating point expressions such as herbie which may be useful if you can convert your expression to C/C++/FORTRAN. Oct 16 at 13:26
• @flinty in this case, I am not concerned about precision, but rather the fact that the solution provided by DSolve is in a form that leads to precision errors unnecessarily. Is there any software design philosophy that would justify why Wolfram doesn't effectively apply Simplify to their core functions? Oct 16 at 20:56