2012-11-01 53 views
0

我目前正在为我的大学学习做一个python练习。我很卡在这个任务:泰勒多项式计算

度N代表的指数函数e泰勒多项式^ x由下式给出:

 N 
p(x) = Sigma x^k/k! 
k = 0 

作出这样(下找到)(一)进口类多项式程序,(ii)从命令行读取x和一系列N值,(iii)创建表示泰勒多项式的多项式实例,并且(iv)针对给定N值打印p(x)的值以及确切的价值e^x。尝试出程序,其中x = 0.5,3,10和N = 2,5,10,15,25

Polynomial.py

import numpy 

class Polynomial: 
def __init__(self, coefficients): 
    self.coeff = coefficients 

def __call__(self, x): 
    """Evaluate the polynomial.""" 
    s = 0 
    for i in range(len(self.coeff)): 
     s += self.coeff[i]*x**i 
    return s 

def __add__(self, other): 
    # Start with the longest list and add in the other 
    if len(self.coeff) > len(other.coeff): 
     result_coeff = self.coeff[:] # copy! 
     for i in range(len(other.coeff)): 
      result_coeff[i] += other.coeff[i] 
    else: 
     result_coeff = other.coeff[:] # copy! 
     for i in range(len(self.coeff)): 
      result_coeff[i] += self.coeff[i] 
    return Polynomial(result_coeff) 

def __mul__(self, other): 
    c = self.coeff 
    d = other.coeff 
    M = len(c) - 1 
    N = len(d) - 1 
    result_coeff = numpy.zeros(M+N+1) 
    for i in range(0, M+1): 
     for j in range(0, N+1): 
      result_coeff[i+j] += c[i]*d[j] 
    return Polynomial(result_coeff) 

def differentiate(self): 
    """Differentiate this polynomial in-place.""" 
    for i in range(1, len(self.coeff)): 
     self.coeff[i-1] = i*self.coeff[i] 
    del self.coeff[-1] 

def derivative(self): 
    """Copy this polynomial and return its derivative.""" 
    dpdx = Polynomial(self.coeff[:]) # make a copy 
    dpdx.differentiate() 
    return dpdx 

def __str__(self): 
    s = '' 
    for i in range(0, len(self.coeff)): 
     if self.coeff[i] != 0: 
      s += ' + %g*x^%d' % (self.coeff[i], i) 
    # Fix layout 
    s = s.replace('+ -', '- ') 
    s = s.replace('x^0', '1') 
    s = s.replace(' 1*', ' ') 
    s = s.replace('x^1 ', 'x ') 
    #s = s.replace('x^1', 'x') # will replace x^100 by x^00 
    if s[0:3] == ' + ': # remove initial + 
     s = s[3:] 
    if s[0:3] == ' - ': # fix spaces for initial - 
     s = '-' + s[3:] 
    return s 

def simplestr(self): 
    s = '' 
    for i in range(0, len(self.coeff)): 
     s += ' + %g*x^%d' % (self.coeff[i], i) 
    return s 


def _test(): 
    p1 = Polynomial([1, -1]) 
    p2 = Polynomial([0, 1, 0, 0, -6, -1]) 
    p3 = p1 + p2 
print p1, ' + ', p2, ' = ', p3 
p4 = p1*p2 
print p1, ' * ', p2, ' = ', p4 
print 'p2(3) =', p2(3) 
p5 = p2.derivative() 
print 'd/dx', p2, ' = ', p5 
print 'd/dx', p2, 
p2.differentiate() 
print ' = ', p5 
p4 = p2.derivative() 
print 'd/dx', p2, ' = ', p4 

if __name__ == '__main__': 
_test() 

现在我确实停留在此,我很想得到一个解释!我应该写我的代码在一个单独的文件。我正在考虑制作一个Polynomial类的实例,并在argv [2:]列表中发送,但这似乎不起作用。在发送到多项式类之前,我是否必须作出def来计算不同N值的泰勒多项式?

任何帮助是很大的,在此先感谢:)

回答

2

没有完全结束,但是这个回答您的主要问题,我相信。将类Polynomial放入poly.p并导入它。

from poly import Polynomial as p 
from math import exp,factorial 

def get_input(n): 
    ''' get n numbers from stdin ''' 
    entered = list() 
    for i in range(n): 
     print 'input number ' 
    entered.append(raw_input()) 
    return entered 

def some_input(): 
    return [[2,3,4],[4,3,2]] 



get input from cmd line                                 
n = 3                                      
a = get_input(n)                                   
b = get_input(n)                                   


#a,b = some_input() 

ap = p(a) 
bp = p(b) 


print 'entered : ',a,b 

c = ap+bp 

print 'a + b = ',c 

print exp(3) 

x = ap 
print x 

sum = p([0]) 
for k in range(1,5): 
    el = x 
    for j in range(1,k): 
     el el * x 
     print 'el: ',el 
    if el!=None and sum!=None: 
     sum = sum + el 
     print 'sum ',sum 

输出

entered : [2, 3, 4] [4, 3, 2] 
a + b = 6*1 + 6*x + 6*x^2 
20.0855369232 
2*1 + 3*x + 4*x^2 
sum 2*1 + 3*x + 4*x^2 
el: 4*1 + 12*x + 25*x^2 + 24*x^3 + 16*x^4 
sum 6*1 + 15*x + 29*x^2 + 24*x^3 + 16*x^4 
el: 4*1 + 12*x + 25*x^2 + 24*x^3 + 16*x^4 
el: 8*1 + 36*x + 102*x^2 + 171*x^3 + 204*x^4 + 144*x^5 + 64*x^6 
sum 14*1 + 51*x + 131*x^2 + 195*x^3 + 220*x^4 + 144*x^5 + 64*x^6 
el: 4*1 + 12*x + 25*x^2 + 24*x^3 + 16*x^4 
el: 8*1 + 36*x + 102*x^2 + 171*x^3 + 204*x^4 + 144*x^5 + 64*x^6 
el: 16*1 + 96*x + 344*x^2 + 792*x^3 + 1329*x^4 + 1584*x^5 + 1376*x^6 + 768*x^7 + 256*x^8 
sum 30*1 + 147*x + 475*x^2 + 987*x^3 + 1549*x^4 + 1728*x^5 + 1440*x^6 + 768*x^7 + 256*x^8 
+0

哇,非常感谢。这确实回答了我的问题。谢谢! :) –

1

我解决了以下方式的任务,但林不知道,如果它回答的问题(四)。 输出只是将e ** x的精确值与模块Polynomial中的计算值进行比较。

from math import factorial, exp 
from Polynomial import * 
from sys import * 

#Reads x and N from the command line on the form [filename.py, x-value, N-value] 
x = eval(argv[1]) 
N = eval(argv[2]) 

#Creating list of coefficients on the form [1/i!] 
list_coeff = [1./factorial(i) for i in range(N)] 

print list_coeff 

#Creating an instance of class Polynomial 
p1 = Polynomial(list_coeff) 

print 'Calculated value of e**%f = %f ' %(x, p1.__call__(x)) 
print 'Exact value of e**%f = %f'% (x, exp(x)) 

"""Test Execution 
Terminal > python Polynomial_exp.py 0.5 5 
[1.0, 1.0, 0.5, 0.16666666666666666, 0.041666666666666664] 
Calculated value of e**0.500000 = 1.648438 
Exact value of e**0.500000 = 1.648721 
"""