(Some function) is not defined with SymPy Lambdify

So, I am writing a script that evaluates Taylor series. However, I want it to evaluate all types of functions. So I tried, for example, to use a function acot(x)

.

x = sy.Symbol('x')
f = acot(x)
...
func = taylor(f,0,3)
taylor_lambda = sy.lambdify(x, func, 'numpy')

      

The above works without exception (except if I use acsch

for example and doesn't start).

But then when it reaches this line:

plt.plot(x1,taylor_lambda(x1),label='taylor approximation')

      

I get:

NameError: name 'acot' is not defined

      

I tried replacing numpy

with sympy

by a call to lambdify, but this seems to be symbolically evaluated. This happens with some (rarer features), but not others. Thank!

My import looks like this:

import sympy as sy
import numpy as np
from sympy.functions import *
from sympy import pi, E,acot
import matplotlib.pyplot as plt
import math

      

+3


source to share


2 answers


I've had similar problems before and managed to fix them. Your line

plt.plot(x1,taylor_lambda(x1),label='taylor approximation')

      



looks ok. I give one of my old code that works great, you can just compare.

from sympy.abc import x
from sympy import sin, series
from sympy.utilities.lambdify import lambdify

import numpy as np
import matplotlib.pyplot as plt


func = sin(x)/x
taylor = series(func, n=6).removeO()

evalfunc = lambdify(x, func, modules=['numpy'])
evaltaylor = lambdify(x, taylor, modules=['numpy'])

t = np.linspace(-7.5, 7.5 , 100)
plt.plot(t, evalfunc(t), 'b', label='sin(x)/x')
plt.plot(t, evaltaylor(t), 'r', label='Taylor')
plt.legend(loc='best')
plt.show()

      

+2


source


The main problem here is that the function lambdify

uses an argument modules

to determine the available modules for the supplied function. Seems acot

not available in namespace numpy

.

Lets reduce this to simple:

import sympy as sy
import numpy as np
from sympy.functions import *

x = sy.Symbol('x')
f = acot(x)
func_lambda = sy.lambdify(x, f, modules='numpy')
print(func_lambda(1))

      

The value arises NameError

because it is acot

not defined in the namespace numpy

. Notice the modules argument. If we expand the available modules to sympy

, we no longer get NameError

:

func_lambda = sy.lambdify(x, f, modules=['numpy', 'sympy'])
print(func_lambda(1))
# Prints pi/4

      



If you're having trouble with odd functions, you can also add the individual functions to the lambdify modules parameter as a dictionary func_name

: function

pairs:

func_lambda = sy.lambdify(x, f, modules=['numpy', {'acot':acot}])
print(func_lambda(1))
# Prints pi/4

      

As for plotting a plot using matplotlib, vectorizing the equation and then plotting work for me:

import matplotlib.pyplot as plt
vfunc = np.vectorize(func_lambda)
x1 = np.linspace(-10, 10 , 1000)
plt.plot(x1, vfunc(x1),label='acot')
plt.show()

      

+2


source







All Articles