Finding C[i]'s expression in DSolve solution
It's possible to dig out C[_]
directly from DSolve
, with the help of TraceInternal
:
eqn = y''[x] - 4 y[x] == 1;
constant =
Trace[DSolve[{eqn, y[0] == 1, y'[1] == -1}, y[x], x], HoldPattern[C[_] -> _],
TraceInternal -> True] // Flatten // ReleaseHold // Simplify // Union
(* {C[1] -> (5 - 2 E^2)/(4 + 4 E^4), C[2] -> (2 E^2 + 5 E^4)/(4 + 4 E^4)} *)
Or a bit shorter:
constant = Trace[DSolve[{eqn, y[0] == 1, y'[1] == -1}, y[x], x],
HoldPattern[{(C[_] -> _) ..}], TraceInternal -> True] // ReleaseHold // Flatten
The most obvious answer is to solve for the constants from the general solution directly. In this example, let
gensol = DSolve[y''[x] - 4 y[x] == 1, y[x], x][[1, 1, 2]]
(*-(1/4) + E^(2 x) C[1] + E^(-2 x) C[2]*)
Now we can construct a system of equations based on the boundary conditions specified in the problem to get explicit values for our general solution constants.
FullSimplify@
Solve[{Evaluate[gensol /. x -> 0] == 1,
Evaluate[D[gensol, x] /. x -> 1] == -1}, {C[1], C[2]}]
(*{{C[1] -> (5 - 2 E^2)/(4 + 4 E^4),
C[2] -> (2 E^2 + 5 E^4)/(4 + 4 E^4)}}*)
In this example we also mess around a bit with the full solution to extract the general solution constants.
totsol = DSolve[{y''[x] - 4 y[x] == 1, y[0] == 1, y'[1] == -1}, y[x],
x][[1, 1, 2]]
(*-((E^(-2 x) (-2 E^2 - 5 E^4 + E^(2 x) - 5 E^(4 x) + E^(4 + 2 x) +
2 E^(2 + 4 x)))/(4 (1 + E^4)))*)
Collecting the results based on one of the functions appearing in the general solution we can extract the constants.
Collect[Expand[totsol], E^(2 x)]
(*-(1/(4 (1 + E^4))) - E^4/(4 (1 + E^4)) +
E^(2 x) (5/(4 (1 + E^4)) - E^2/(2 (1 + E^4))) +
E^(-2 x) (E^2/(2 (1 + E^4)) + (5 E^4)/(4 (1 + E^4)))*)
We can now simplify things a bit to get the constants.
FullSimplify[-(1/(4 (1 + E^4))) - E^4/(4 (1 + E^4))]
(*-(1/4)*)
FullSimplify[{(5/(4 (1 + E^4)) - E^2/(2 (1 + E^4))), (E^2/(
2 (1 + E^4)) + (5 E^4)/(4 (1 + E^4)))}]
(*{(5 - 2 E^2)/(4 + 4 E^4), (2 E^2 + 5 E^4)/(4 + 4 E^4)}*)
Checking that we get the same answer in both methods:
FullSimplify[{(5/(4 (1 + E^4)) - E^2/(2 (1 + E^4))), (E^2/(
2 (1 + E^4)) + (5 E^4)/(4 (1 + E^4)))}] ==
Flatten@FullSimplify@
Solve[{Evaluate[gensol /. x -> 0] == 1,
Evaluate[D[gensol, x] /. x -> 1] == -1}, {C[1],
C[2]}][[;; , ;; , 2]]
(*True*)
If you do it the following way, applying the shown rules, you get the desired result.
This can be used for all types of equations.
dsol = First@DSolve[y''[x] - 4 y[x] == 1, y, x]
(* {y -> Function[{x}, -(1/4) + E^(2 x) C[1] + E^(-2 x) C[2]]} *)
sol = First@Solve[{y[0] == a, y'[0] == b} /. dsol, {C[1], C[2]}]
(* {C[1] -> 1/8 (1 + 4 a + 2 b), C[2] -> 1/8 + a/2 - b/4} *)
ys[x_, a_, b_] = (y[x] /. dsol /. sol)
(* -(1/4) + (1/8 + a/2 - b/4) E^(-2 x) + 1/8 (1 + 4 a + 2 b) E^(2 x) *)