Search code examples
pythonsympyabsolute-value

Differentiating absolute value functions using sympy in python won't return an answer


I'm trying to find the maximum points of curvature of a tanh(x) function, but the mathematical definition for curvature contains an absolute value function. I've specified that x must be real-valued which resolves sympy returning an imaginary function for the derivative of the curvature. However when trying to solve for k'(x)=0 using the sym.solve() method python will simply continue running and not return an answer at all.

x = sym.symbols('x', real=True)

# below are parameters I found from curve fitting raw data elsewhere that are just converted to sympy variables

a = sym.Float(a)  
b = sym.Float(b)
c = sym.Float(c)
d = sym.Float(d)

# function in question
def f(x):
    return a * sym.tanh(b * x + c) + d

def fprime(x):
    return sym.diff(f(x),x,1)

def f2prime(x):
    return sym.diff(f(x),x,2)

f1 = fprime(x)
f2 = f2prime(x)

# mathematical definition of curvature
def kappa(f1,f2):
    return sym.Abs(f2) / ( 1 + f1**2 )**(3/2)

def kprime(f1,f2):
    return sym.diff(kappa(f1,f2),x,1)

k1 = kprime(f1,f2)
print(k1)

One combination of the constants a,b,c,d=[-2.40402847 -3.20154993 0.51489147 -8.05771537] and k1 was

0.324273723818531*(1 - tanh(0.514891472285591 - 3.2015499273203*x)**2)*((1 - tanh(0.514891472285591 - 3.2015499273203*x)**2)**2 + 0.0168810800591381)**(-2.5)*(6.40309985464061*tanh(0.514891472285591 - 3.2015499273203*x)**2 - 6.40309985464061)*tanh(0.514891472285591 - 3.2015499273203*x)*Abs((tanh(3.2015499273203*x - 0.514891472285591)**2 - 1)*tanh(3.2015499273203*x - 0.514891472285591)) + 0.108091241272844*((3.2015499273203 - 3.2015499273203*tanh(3.2015499273203*x - 0.514891472285591)**2)*(tanh(3.2015499273203*x - 0.514891472285591)**2 - 1) + (6.40309985464061 - 6.40309985464061*tanh(3.2015499273203*x - 0.514891472285591)**2)*tanh(3.2015499273203*x - 0.514891472285591)**2)*((1 - tanh(0.514891472285591 - 3.2015499273203*x)**2)**2 + 0.0168810800591381)**(-1.5)*sign((tanh(3.2015499273203*x - 0.514891472285591)**2 - 1)*tanh(3.2015499273203*x - 0.514891472285591))

Then trying to solve this for x using print(sym.solve(k1),x) could never return an answer.


Solution

  • It's a pretty high-order nonlinear equation. Try nsolve:

    >>> nsolve(k1, -.5)
    -0.427127686132521