Search code examples
pythonsympylogarithm

Logarithms in sympy


Please tell me how you can change log(e) to 1. And in general is there a way in sympy to get a float-type answer? For example, instead of log(2), get 0.69314718056

from math import *
from sympy import *

x1=symbols('x1')
x2=symbols('x2')
Func = e**(2*x1)*(x1+x2**2+2*x2)
print(Func.diff(x2))

Here I already get log(e). In other calculations, the same situation


Solution

  • The problem is that you are mixing the math module and sympy. This leads to "inconsistent" results. Note that in your code, e comes from the math module, and it is just the number 2.71828182845905. SymPy also exposes the Euler's number, but it is called E, which is a symbolic entity.

    Hence, when working with SymPy, try to use as many SymPy objects as possible. Your expression becomes:

    Func = E**(2*x1)*(x1+x2**2+2*x2)
    

    By using SymPy objects, canonical simplifications are possible: log(E) gives 1.

    If you want to convert "symbolic numbers" to floating point, you can use the n() method. For example log(2).n() gives 0.693147180559945.