问题
Beginner programmer here looking to write a function that can simply derive a mathematical function.
The function should run like this:
f(x) = x ** 2 + 2 * x <--- user input
f'(x) = 2 * x + 2
I know there's Wolfram and Maple, but I want to write my own actual derivative program. I would like to know if this is possible.
回答1:
It's obviously possible, as there are plenty of programs out there that do symbolic differentiation. That being said, it's non trivial. For your simple example above, you'd need to write a parser that would:
- split up each of the terms of polynomial
- parse the term and break it down to coefficient, variable, and exponent
- Apply the power rule
- String together the outputs
That would only handle this very basic type of derivative - no chain rule, product rule, etc, and you'd have to implement each of those separately.
So yes, definitely doable, but also non-trivial.
回答2:
This is called symbolic differentation.
You need to parse the equation into tree of expressions and operations, then apply the normal rules of differentation (from Calculus I) to the tree.
回答3:
of course you can spend some days to write your own differentiate program (and fortunately differentiation is quite simple), but if this is not an exercise, you can actually use something ready, for example you can use sympy:
import sympy
x = sympy.Symbol('x')
sympy.diff(x**2+2*x, x)
# return: 2*x + 2
回答4:
There's a good basic symbolic differentiation example in SICP. It's scheme, not python, but should be easy enough to translate once you've dealt with parsing your input.
回答5:
It's absolutely possible. You'll first need to parse the user's input string to get a representation of the function that you can work with. You'll then need to process the various terms in the function according the the differentiation rules you want to support.
来源:https://stackoverflow.com/questions/12829395/deriving-a-mathematical-function-in-python