簡體   English   中英

Python:如何僅使用數學模塊集成數學函數?

[英]Python: How to integrate a math function using only math module?

剛開始學習python,並被要求定義一個集成數學函數的python函數。

我們被告知python函數必須采用以下形式:(例如,計算x=1x=2之間的y = 2x + 3的面積)

integrate( 2 * x + 3, 1, 2 )

(它應該返回下面的區域)

並且除math之外,我們不允許使用/ import任何其他庫(也不允許使用內置的集成工具)。

知道我應該怎么做嗎? 在編寫程序時,我總是得到x是未定義的,但是如果我將x定義為一個值(假設為0),則參數中的2*x+3部分始終被視為一個值,而不是數學方程式,因此我真的不能在里面使用它嗎?

這將非常有幫助,不僅對這種分配,而且對將來的許多工作,如果我知道python函數如何將數學方程式作為參數,那么非常感謝。

假設您的集成函數如下所示:

def integrate(func, lo_x, hi_x):
    #... Stuff to perform the integral, which will need to evaluate
    # the passed function for various values of x, like this
    y = func(x)
    #... more stuff
    return value

然后您可以這樣稱呼它:

value = integrate(lambda x: 2 * x + 3, 1, 2)

編輯

但是,如果在調用集成功能必須完全一樣

integrate( 2 * x + 3, 1, 2 )

那么事情就有點棘手了。 如果您知道使用多項式函數調用該函數,則可以通過將x設為多項式類的實例來實現,如M. ArthurVaïsse在其答案中所建議的。

或者,如果integrate( 2 * x + 3, 1, 2 ) raw_input() integrate( 2 * x + 3, 1, 2 )來自字符串,例如來自命令行參數或raw_input()調用,則可以從命令行中提取2 * x + 3 (或其他值)使用標准Python字符串方法創建字符串,然后使用exec從該函數構建lambda函數。

這里有一個滿足我需求的實現。 它允許您定義數學函數(例如2x + 3),並提出逐步計算的實現方案,如此處所述[ http://en.wikipedia.org/wiki/Darboux_integral]

import math

class PolynomialEquation():
    """ Allow to create function that are polynomial """
    def __init__(self,coef):
        """ 
        coef : coeficients of the polynome.

        An equation initialized with [1,2,3] as parameters is equivalent to:
            y = 1 + 2X + 3X²

        """
        self.coef = coef

    def __call__(self, x):
        """
        Make the object callable like a function.
        Return the value of the equation for x
        """
        return sum( [self.coef[i]*(x**i) for i in range(len(self.coef)) ])

def step_integration(function, start, end, steps=100):
    """ 
    Proceed to a step integration of the function.
    The more steps there are, the more the approximation is good.
    """
    step_size = (end-start)/steps
    values = [start + i*step_size for i in range(1,steps+1)]
    return sum([math.fabs(function(value)*step_size) for value in values])


if __name__ == "__main__":
    #check that PolynomialEquation.value works properly. Assert make the program crash if the test is False.

    #y = 2x+3 -> y = 3+2x -> PolynomialEquation([3,2])
    eq = PolynomialEquation([3,2])
    assert eq(0) == 3
    assert eq(1) == 5
    assert eq(2) == 7

    #y = 1 + 2X + 3X² -> PolynomialEquation([1,2,3])
    eq2 = PolynomialEquation([1,2,3])
    assert eq2(0) == 1
    assert eq2(1) == 6
    assert eq2(2) == 17

    print(step_integration(eq, 0, 10))
    print(step_integration(math.sin, 0, 10))

編輯:實際上,實現僅是上達布克斯積分。 如果確實需要,可以通過計算較低的Darboux積分(用step_integration函數中的range(steps)range(1, steps+1)替換為range(steps)來計算真正的Darboux積分, step_integration得到較低的Darboux函數。根據您的精度需要,兩個Darboux函數之間的差值是否大於一個小值(例如,可以為0.001),因此假設100步積分可以使您對積分值有一個近似的估計。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM