如何遍历字母列表以分配浮点值以创建多项式?

How can I iterate through a list of letters to assign float values to create a polynomial?

我正在尝试通过梯形法对多项式函数求积分(稍后我可以更改为更准确的方法)。我的代码并不完美,我想确切地了解它为什么不起作用。我遇到的一个问题是 while 循环没有结束。到目前为止,我的代码如下。

    def Integrate_Trapezoidal(x_LoBound,x_HiBound,N):
        """
        INPUT   :
                    x_LoBound   --      lower bound of integral
                    x_HiBound   --      upper bound of integral
                    N           --      number of slices (N --> inf ==> integral)
        OUTPUT  :
                                --      approximate value of integral
        """
        ## CREATE ALPHABET
        alphabet = [chr(i) for i in range(ord('a'),ord('z')+1)]
        ## alphabet = ['a','b','c',...,'z'] ##
        ## WOULD LOVE TO TRY FLOATING INPUTS VIA ARRAY COMPREHENSION
        a = float(input("What is the coefficient of the lowest order term:  "))
        CoeffList = []
        CoeffNumList = []
        LengthCoeffList = [] ## [1,2,3,...,max] where max = coefficient of highest-order term
        for letter in alphabet:
            AddOne = int(1)
            AddOne += int(1)
            for i in range(int(1),int(AddOne)):
                letter = alphabet[int(i)]
                while letter in alphabet:
                    CoeffList.append(letter)
                    LengthCoeffList.append(len(CoeffList))
                    # alphabet[i]
                    # i = i + 1
                    letter = float(input("What is the coefficient of the next-order term:  ")) ## GO FROM a = ___ TO b = ___ TO c = ___ ...
                    CoeffNumList.append(letter)
                    if float(input("What is the coefficient of the next-order term:  ")) == '0':
                        print("Type 'Y for YES and 'N' for NO")
                        YESorNO = str(input("Is that the last term of the polynomial:  "))
                        endterm = YESorNO[-1] ## look at last character of string
                        if endterm == 'N' or endterm == 'n' or endterm == 'no' or endterm == 'NO' or endterm == 'No':
                            pass
                        elif endterm == 'Y' or endterm == 'y' or endterm == 'YES' or endterm == 'yes' or endterm == 'Yes':
                            break
                            def f(x):
                                """
                                INPUT   :
                                                   x    --  variable of function
                                                        EX: x = x_LoBound OR x = x_HiBound
                                OUTPUT  :
                                            function    --  f(x) = a x^0 + b x^1 + ...
                                                        EX: f(x_LoBound) OR f(x_HiBound)
                                """
                                for expval in LengthCoeffList and CoeffNum in CoeffNumList:
                                    # function = 0
                                    function += CoeffNum * x**expval
                                    return function
                    letter = alphabet[int(i+1)] ## GO FROM a TO b TO c ...
        ## TRAPEZOIDAL RULE
        # def f(x):
        #     return x**4 - 2*x + 1
        ht = (x_HiBound - x_LoBound) / N
        ss = 0.5 * f(x_LoBound) + 0.5 * f(x_HiBound)
        for num in range(1,N):
            ss += f(x_LoBound + num*ht)
        return ht*ss
    checkanswer = Integrate_Trapezoidal(0,2,10)
    print(checkanswer)

我查看了您的代码并找到了一些我认为可行的代码,并对照我下载的几份大学讲义进行了检查。正如您在评论中所说,有很多不必要的额外列表,所以我在那里削减了很多代码。

特别是,如果假设每个系数是从低到高的顺序添加的,并且为任何不存在的添加0,则您只需要列表中的元素编号即可知道x的力量。

我还移动了 f() 的定义以创建辅助函数 solve_point(),它的工作方式与我认为的相同。特别是,sumenumerate 是内置的,enumerate 遍历 coeff_list 并返回一个计数以给出幂(0 向上)。

get_coefficients() 来自您的旧 Integrate_Trapezoidal(),但更专注于一件事 - 这就是为什么它然后 returns CoeffList 最终被处理的原因。

def solve_point(x, coeff_list):
    return sum(coeff * x**e for e, coeff in enumerate(coeff_list))


def get_coefficients():
    CoeffList = []
    while True:
        # GO FROM a = ___ TO b = ___ TO c = ___ ...
        coeff = float(input("What is the coefficient of the next-order term:  "))
        CoeffList.append(coeff)
        if coeff == 0:
            YESorNO = raw_input("Is that the last term of the polynomial: [Y/N]  ")
            if YESorNO.upper() == 'Y':
                return CoeffList[:-1]

lo, hi, n = 0, 2, 6
coeff_list = get_coefficients()

ht = (hi - lo) / float(n)
ss = 0.5 * solve_point(lo, coeff_list) + 0.5 * solve_point(hi, coeff_list)
for num in range(1,n):
    ss += solve_point(lo + num*ht, coeff_list)
checkanswer = ht*ss


print(checkanswer)

我认为它是正确的 - 我已经做了几次检查。希望对您的重写有所帮助!如果您有任何不起作用的示例,很高兴知道,或者您可以看到任何错误...