利用Python进行简单的求导
代码:class Monomial:def __init__(self, term=1, times=1, have_space = True):
self.term = term
self.times = times
self.have_space = have_space
def derivate(self):
return Monomial(self.term*self.times, self.times-1)
def __repr__(self):
if self.times == 0:
return str(self.term)
else:
return str(self.term) + \
(' ' if self.have_space else '') + \
'*' + \
(' ' if self.have_space else '') + \
'x' + \
(' ' if self.have_space else '') + \
'^' + \
(' ' if self.have_space else '') + \
str(self.times)
def __str__(self):
if self.times == 0:
return str(self.term)
else:
return str(self.term) + \
(' ' if self.have_space else '') + \
'*' + \
(' ' if self.have_space else '') + \
'x' + \
(' ' if self.have_space else '') + \
'^' + \
(' ' if self.have_space else '') + \
str(self.times)
class Polynomial:
def __init__(self, formula, have_space = True):
self.have_space = have_space
self.formula = formula.split('+')
self.formula =
for i in range(len(self.formula)):
temp = self.formula
if not(len(temp) == 5 and temp == 'x' and temp == '^' and temp == '*'):
raise TypeError
self.formula = Monomial(int(temp), int(temp), self.have_space)
def derivate(self):
import copy
temp = copy.copy(self)
#print(temp)
del copy
for i in range(len(temp.formula)):
#print(temp.formula, type(temp.formula))
temp.formula = temp.formula.derivate()
return temp
def __str__(self):
temp = ''
for i in range(len(self.formula)):
temp += str(self.formula)
return temp
def __repr__(self):
temp = ''
for i in range(len(self.formula)):
temp += repr(self.formula)
return temp
演示:>>> x = Polynomial('1*x^5+1*x^4')
>>> x
1 * x ^ 5 + 1 * x ^ 4
>>> x.derivate()
5 * x ^ 4 + 4 * x ^ 3
>>> y = Polynomial('3*x^5', False)
>>> y
3*x^5
>>> y.derivate()
15 * x ^ 4
>>>
缺点:
1. 输入的多项式只能是包含x的式子,并且必须是1 * x ^ 5这种形式(不能写成x^5)
2. 不能输入ln sin cos tan 等函数
3. 不能输入 (x+1)^2 这种式子
总的来说,就是特别简单,限制很多{:10_266:} zhichi
页:
[1]