如何编写这个函数并计算积分?

2024-10-02 00:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python定义这个函数:

F(s) = integration(f(x, a), 0, s)

其中f(x, a)可以是x的任何函数。这里a是一个常数。你知道吗

例如:f(x,2)=exp(2*x/(2+x))

并在Python中计算其集成度:

value = integration(F(rho)-F(s),0,rho)   # here rho is a given constant.

到目前为止,我已经手工计算了“f”(不是上面的函数)的积分,然后使用fromscipy.integrateimport quad来计算最后的积分。但是,手工计算每个函数的积分是不可能的。例如,上述函数“f”。你知道吗


Tags: 函数here定义isvalue常数integrationgiven
1条回答
网友
1楼 · 发布于 2024-10-02 00:23:44
def integration(f,a,b):
    """
    compute the integrale of f on [a, b]
    :param f: function
    :param a: left point of the interval
    :param b: right point of the interval
    :return: the value of the integrale
    """
    # we can use for instance the rectangle methods, but any method would be ok (the trapezoid method also...)
    N = 1000  # number of point you want to sample
    h = 1/(N+1)  # the discretization step
    integral = 0
    for k in range(N + 1):
        point = a + h*k
        integral += h * f(point)

    return integral

import numpy as np
print("with integration method", integration(np.exp, 0, 1))
print("by hand", np.exp(1) - 1)
print("difference", abs(integration(np.exp, 0, 1) - (np.exp(1) - 1)))

print("\n")
print("Now let's try with this function exp(2*x/(2+x))")
print("with integration method", integration(lambda x: np.exp(2*x / (2 + x)), 0, 1))

相关问题 更多 >

    热门问题