(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).

q[t_] := Evaluate[q[t] /. First@
   DSolve[{v Sin[2 Pi f t] - q'[t] r - q[t]/c == 0, q[0] == 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}]

enter image description here

...which goes away if we Expand:

Plot[Expand[q[t]]/c /. fp, {t, 0, 10}]

enter image description here

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.


enter image description here

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]

enter image description here

It does not appear that there is a built in method for obtaining coefficients from a user defined series (e.g. CustomCoefficients[<expr>, <pattern>])

  • 2
    $\begingroup$ 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. $\endgroup$
    – Michael E2
    Oct 15 at 19:41
  • $\begingroup$ @MichaelE2 That does reveal the problem right away. $\endgroup$ Oct 15 at 22:28
  • $\begingroup$ 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. $\endgroup$
    – flinty
    Oct 16 at 13:26
  • $\begingroup$ @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? $\endgroup$ Oct 16 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.