[英]How can I simplify this more?
我正在尝试将numpy应用于我为梯形规则集成编写的这段代码:
def integral(a,b,n):
delta = (b-a)/float(n)
s = 0.0
s+= np.sin(a)/(a*2)
for i in range(1,n):
s +=np.sin(a + i*delta)/(a + i*delta)
s += np.sin(b)/(b*2.0)
return s * delta
我正在尝试从新函数中获取返回值,如下所示:
return delta *((2 *np.sin(x[1:-1])) +np.sin(x[0])+np.sin(x[-1]) )/2*x
我已经尝试了很长时间了,但我的所有尝试都以失败告终。
我尝试但没有得到的一件事是为什么以下代码too many indices for array
错误提供了too many indices for array
?
def integral(a,b,n):
d = (b-a)/float(n)
x = np.arange(a,b,d)
J = np.where(x[:,1] < np.sin(x[:,0])/x[:,0])[0]
每个提示/建议都非常感谢。
您忘了总结sin(x)
:
>>> def integral(a, b, n):
... x, delta = np.linspace(a, b, n+1, retstep=True)
... y = np.sin(x)
... y[0] /= 2
... y[-1] /= 2
... return delta * y.sum()
...
>>> integral(0, np.pi / 2, 10000)
0.9999999979438324
>>> integral(0, 2 * np.pi, 10000)
0.0
>>> from scipy.integrate import quad
>>> quad(np.sin, 0, np.pi / 2)
(0.9999999999999999, 1.1102230246251564e-14)
>>> quad(np.sin, 0, 2 * np.pi)
(2.221501482512777e-16, 4.3998892617845996e-14)
同时,我也尝试过。
import numpy as np
def T_n(a, b, n, fun):
delta = (b - a)/float(n) # delta formula
x_i = lambda a,i,delta: a + i * delta # calculate x_i
return 0.5 * delta * \
(2 * sum(fun(x_i(a, np.arange(0, n + 1), delta))) \
- fun(x_i(a, 0, delta)) \
- fun(x_i(a, n, delta)))
使用本页底部的公式重建代码https://matheguru.com/integralrechnung/trapezregel.html
使用numpy实现范围(0,n + 1)的求和-给出[0,1,...,n]。 通常,您将在普通Python中使用for循环来收集值。 但是这里可以使用numpy的矢量化行为。 np.arange(0,n + 1)给出一个np.array([0,1,...,n])。
如果将其作为函数的参数(此处抽象为fun
),则将计算x_0
到x_n
的函数公式。 并收集在一个numpy数组中。 所以fun(x_i(...))
将应用于x_0
的函数的numpy数组返回给x_n
。 该数组/列表由sum()
。
将整个sum()
乘以2
,然后将x_0和x_n的函数值相减。 (因为在梯形公式中,只有中间被乘数,而不是第一个和最后一个被乘以2)。 这有点像黑客。
链接的德语页面使用fun(x) = x ^ 2 + 3
作为函数,可以使用lambda表达式动态定义它:
fun = lambda x: x ** 2 + 3
a = -2
b = 3
n = 6
您也可以改用普通的函数定义: defun fun(x): return x ** 2 + 3
。 因此,我通过键入以下命令进行了测试:
T_n(a, b, n, fun)
正确返回的是:
## Out[172]: 27.24537037037037
对于您的情况,只需将np.sin
分配给fun
并将a
, b
和n
值分配给该函数调用。
喜欢:
fun = np.sin # by that eveywhere where `fun` is placed in function,
# it will behave as if `np.sin` will stand there - this is possible,
# because Python treats its functions as first class citizens
a = #your value
b = #your value
n = #your value
最后,您可以致电:
T_n(a, b, n, fun)
它将起作用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.