Steve
Steve

Reputation: 13

I'm trying to define a function an its derivative but it seems to not be working

So I want to make code to use a numerical method of approximation and I need the function and its derivative, so I did this:

    import numpy as np
    import sympy as sym
    import math
    x = Symbol('x')
    fx = lambda x:math.tan(2*(x-5*math.pi/2))-x
    f = math.tan(2*(x-5*math.pi/2))-x
    dfx = lambdify (x,f.diff(x))

This is the error, it worked before when I used polynomial functions:

    TypeError        Traceback (most recent call last)
    <ipython-input-18-e3f579396c41> in <module>
          1 # INGRESO
          2 fx = lambda x:math.tan(2*(x-5*math.pi/2))-x
    ----> 3 f = (float)(math.tan(2*(x-5*math.pi/2))-x)
          4 dfx = lambdify (x,f.diff(x))
          5 
    
    ~\Anaconda3\lib\site-packages\sympy\core\expr.py in __float__(self)
        278         if result.is_number and result.as_real_imag()[1]:
        279             raise TypeError("can't convert complex to float")
    --> 280         raise TypeError("can't convert expression to float")
        281 
        282     def __complex__(self):
    

TypeError: can't convert expression to float

Upvotes: 0

Views: 161

Answers (2)

Saikat
Saikat

Reputation: 1

Use sympi tan and pi:math library does not work well with sympy

import sympy as sym
from sympy import tan,pi
import numpy as np

x = sym.Symbol('x')
fx = tan(2*(x-5*pi/2))-x
dfx = sym.lambdify (x,fx)

This works...

Upvotes: 0

Oscar Benjamin
Oscar Benjamin

Reputation: 14500

You should be using e.g. sympy.tan not math.tan. The math.tan function only accepts float inputs and you are passing in a symbolic SymPy expression.

In [10]:     import numpy as np 
    ...:     import sympy as sym 
    ...:     import math 
    ...:     x = Symbol('x') 
    ...:     fx = lambda x:sym.tan(2*(x-5*sym.pi/2))-x 
    ...:     f = sym.tan(2*(x-5*sym.pi/2))-x 
    ...:     dfx = lambdify (x,f.diff(x))                                                                                                                     

In [11]: dfx(1)                                                                                                                                               
Out[11]: 10.548798408083835

Upvotes: 1

Related Questions