[英]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.