Search code examples
sympyintegral

Integration of 1/(1-x) with SymPy gives wrong sign inside the logarithm


I'd like to integrate the following and easyfunction in sympy.

import sympy
x = sympy.symbols('x')
e_a = 1/(1-x)
u_x = sympy.integrate(e_a,x)

print(u_x)
sympy.plot(u_x)

My calculus memories suggests me to get -log(1-x) as a result, while sympy returns -log(x - 1). Can't understand what's wrong with the code...


Solution

  • Both -log(1-x) and -log(x-1) are valid answers. This was discussed on issue tracker, so I quote from there.

    -log(x-1)=-(log(1-x)+log(-1)) by log rules, and log(-1)=i*pi (as e**(i*pi)=-1). -log(x-1) is the same as -log(1-x)-i*pi so the expressions actually differ by a constant, which makes no difference to the result when taking the derivative of the expression.

    and

    This is indeed correct behavior. SymPy doesn't return log(abs(x)) for integrate(1/x) because it isn't valid for complex numbers. Instead, the answer is correct up to an integration constant (which may be complex). All SymPy operations assume that variables are complex by default.

    There are some workarounds suggested at the end of the thread.

    But the bottom line, -log(x-1) is correct, and it is the desired form of answer when x is greater than 1. SymPy does not know if you mean for x to be less than 1 or greater than 1.

    To get a specific antiderivative, integrate from a given initial point. For example, integration starting from 0 gives the antiderivative that is 0 when x=0.

    x, t = sympy.symbols('x t')
    e_a = 1/(1-x)
    u_x = sympy.integrate(e_a, (x, 0, t)).subs(t, x)    
    sympy.plot(u_x)
    

    antider