I'm trying to code an algorithm that uses the ODE function, but I'm getting the wrong result for some input.
for
the correct answer should be:
like it can be seen here: https://www.wolframalpha.com/input?i=dsolve%28x%27%28t%29%3D+1%2F%28C+-+t%29%29
but what I get is:
>>> from sympy import symbols, Eq, Function
>>> from sympy import pprint
>>> from sympy import dsolve
>>> x = Function("x")
>>> t = symbols("t")
>>> C1 = symbols("C1")
>>> eq = Eq(x(t).diff(t) - 1/(C1-t))
>>> pprint(eq)
d 1
──(x(t)) - ────── = 0
dt C₁ - t
>>> pprint(dsolve(eq))
x(t) = C₂ - log(-C₁ + t)
which isn't the correct answer: https://www.wolframalpha.com/input?i=is+-log%28c-x%29+%3D+-log%28x-c%29+%3F
How can I fix the code?
The answer returned here by
dsolveis correct and so is the one given by Wolfram Alpha as well. There is not a unique form for the general solution of an ODE because there are different ways to define the arbitrary constants. Here the difference betweenlog(t - C1)andlog(C1 - t)is justI*piwhich can be absorbed into the arbitrary constantC2. The two different forms for the general solution are both correct but would have different values forC2in order to satisfy the same initial conditions.If you expected everything to be real (rather than complex) then
log(C1 - t)will be defined only fort < C1andlog(t - C1)will be defined only fort > C1. It isn't necessary to return different forms fort < C1andt > C1though because both general solutions given hold for all (complex)t != C1provided you understand that the constantC2is not constrained to be real.