Yago Mj
Yago Mj

Reputation: 1

Unable to get the numerical result for a tanh function in Sympy

I am a python newbie. I am trying to get the two numerical results of the convection formula, but the best code I've created outputs a symbolic list containing the 'Lc' parameter, and not the expected numerical result. Anyone could give me a helping hand, please?

from sympy import var, tanh, solve

def convection ():

    m = 0.9
    Lc = var('Lc')
    rend = 0.8

    f = tanh(m*Lc)/(m*Lc)-rend

    return solve(f,[m,Lc,rend],positive=True)

    # Gotten : [(0.900000000000000, Lc, 1.11111111111111*tanh(0.9*Lc)/Lc)]
    # Expected : [0.9, 0.986709867, 0.8] (or something like that)

Thank you in advance.

Upvotes: 0

Views: 197

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14500

Your equation is:

In [33]: m = 0.9

In [34]: Lc = Symbol('Lc')

In [35]: rend = 0.8

In [36]: f = tanh(m*Lc)/(m*Lc)-rend

In [37]: f
Out[37]: 
       1.11111111111111⋅tanh(0.9⋅Lc)
-0.8 + ─────────────────────────────
                     Lc 

The solve function is intended to find analytic solutions but that is often impossible for a transcendental equation such as this.

You are calling solve and asking it to solve for m and rend as well which is just confusing things. You should call it like:

In [38]: solve(f, Lc)
---------------------------------------------------------------------------
NotImplementedError
...
NotImplementedError: multiple generators [Lc, exp(Lc/10)]
No algorithms are implemented to solve equation -4/5 + 10*(exp(9*Lc/10) - exp(-9*Lc/10))/(9*Lc*(exp(9*Lc/10) + exp(-9*Lc/10)))

This fails because the transcendental equation can not be solved in explicit analytic form.

Instead if what you want is a numeric solution you can find that using nsolve:

In [41]: nsolve(f, Lc, 1)
Out[41]: 0.986683032622042

In [42]: nsolve(f, Lc, -1)
Out[42]: -0.986683032622042

Here we have to use an initial guess (e.g. 1 or -1) to seed the numeric solver but then we get a numeric answer.

Upvotes: 1

Related Questions