Sam Paine
Sam Paine

Reputation: 1

Using the sympy library in python I want to find the differential. Here is my code

I basically want to create a program that takes the input from the user in the format 3x^3 and gives a differential in the form 9x**2. However the extension I am using (sympy) requires the initial value to be converted in the form 3x**3 and only then can it be converted to differential.

When I use two different functions it is giving me an eror " AttributeError: 'str' object has no attribute 'diff'" and referring to this line of the code: derivative_f = function_format.diff(x).

I think it is a type error since the first function is returning a string and the second function is unable to process that string.

import sympy as sym


f = str(input("Enter the function: "))


def sanitiseFunction(f):
    f = f.strip()

    if f[0:1] == "x":
        f = "1" + f

    cleaned = ""

    for pos in range(len(f)):

        if f[pos:pos + 1] == "x":

            if isinstance(int(f[pos - 1:pos]), int):
                cleaned = cleaned + "*"

        cleaned = cleaned + f[pos:pos + 1]

    cleaned = cleaned.strip().replace("^", "**")
  
    return cleaned


def symbolicDifferentiation():
    x = sym.Symbol('x')
    function_format = sanitiseFunction(f)
    derivative_f = function_format.diff(x)
    return derivative_f 

print(symbolicDifferentiation())

Upvotes: 0

Views: 96

Answers (1)

smichr
smichr

Reputation: 19115

The "battery is included" to parse strings into SymPy expressions.

>>> def sanitiseFunction(f):
...     from sympy.parsing.sympy_parser import standard_transformations,\
...         implicit_multiplication_application, convert_xor, parse_expr
...     return parse_expr(f, transformations=standard_transformations +
...         (implicit_multiplication_application, convert_xor))
...
>>> sanitiseFunction('3x^3')
3*x**3

Upvotes: 1

Related Questions