Deriving a mathematical function in python [closed]

偶尔善良 提交于 2019-12-23 04:26:11

问题


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:

  1. split up each of the terms of polynomial
  2. parse the term and break it down to coefficient, variable, and exponent
  3. Apply the power rule
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!