1

I've been writing a few programs that, given a math expression (provided as a string in a file), would evaluate f(x) for a given x, using py_expression_eval

Example:

input.txt

x^2 + 1

func.py

from py_expression_eval import Parser

parser = Parser()

file = open("input.txt")

func = file.readline().strip()

f_of_5 = parser.parse(func).evaluate({'x': 2})

output

5

Is there any way I can get the derivative of a function provided as a string like that?

Flayshon
  • 363
  • 1
  • 5
  • 12
  • 1
    Yes, of course you can, but you’ll have to write a derivative algorithm, just like you wrote an evaluate algorithm. This is a pretty good learning exercise if you just want to differentiate polynomials, or if you want to approximate a derivative at a point by numerical means, or something else simple, but you have to pick something specific, read the math on how to do it, and then try to code it. – abarnert Apr 25 '18 at 19:02
  • 1
    Meanwhile, if you want to code up a general-purpose symbolic derivative algorithm, that’s probably way too big to do as a learning project (and if you actually need this for some real work, you’re better off using sympy or some other existing library than trying to build it yourself). – abarnert Apr 25 '18 at 19:03
  • Although it _might_ be an interesting project to build a “sympy compiler” that takes your parse tree and builds a sympy expression that you can then do stuff with. – abarnert Apr 25 '18 at 19:05
  • This is not an exact duplicate since the OP starts with a string. Reopened. – timgeb Apr 25 '18 at 19:07

1 Answers1

2

I've been using sympy for this lately. Here's a small demo:

>>> from sympy import diff, Symbol
>>> from sympy.parsing.sympy_parser import parse_expr
>>>
>>> user_str = 'x**3 + x + 1'
>>> my_symbols = {'x': Symbol('x', real=True)}
>>> my_func = parse_expr(user_str, my_symbols)
>>> my_func
x**3 + x + 1
>>> 
>>> diff(my_func, my_symbols['x'])
3*x**2 + 1
>>> diff(my_func, *3*[my_symbols['x']])
6

Of course, nothing stops you from getting user_str from a file.
(You will have to use ** instead of ^ for exponentiation.)

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • 1
    Thank you! I didn't know about `parse_expr`. Using that + `lambdify()` made my life 10x easier :) – Flayshon Apr 25 '18 at 21:10