我有一個我自己創建的定積分的辛普森規則代碼。出于某種原因,此代碼未輸出正確的值。我當前的函式是 y = x^3,N 的值為 4,a 的值為 0,b 的值為 2。根據辛普森規則,面積必須為 1/6(0^3(4 * (0.5 ^ 3))(2 * (1.0 ^ 3))(4 * (1.5 ^ 3))(2 3))。手動計算,該值正確為 4。但是,在我的程式中,使用相同的邏輯,輸出變為 8,并根據 n 的值進行更改。在我看來,面積不應該僅僅因為 n 更改為另一個正數而發生很大變化。事實上,它應該變得更加精確。你可以從我的代碼中看出我的意思。
def trapezoid(lb, rb, r):
width = (rb-lb)/r
currentX = lb
area = currentX ** 3
yes = "4"
currentX = width
while currentX < rb:
if yes == "4":
area = (4 * (currentX ** 3))
yes = "2"
currentX = width
continue
if yes == "2":
area = (2 * (currentX ** 3))
yes = "4"
currentX = width
continue
area = ((rb) ** 3)
area *= ((rb - lb)/(3 * rb))
return area
lftBount = int(input("Enter the left bound:"))
rgtBount = int(input("Enter the right bound:"))
Repeat = int(input("How many times do you want"))
print(trapezoid(lftBount,rgtBount,Repeat))
我已經在我的腦海和紙上多次解決了這個問題,有人能指出我出錯的方向嗎?
uj5u.com熱心網友回復:
從https://www.intmath.com/integration/6-simpsons-rule.php在我看來,當您將區域除以右邊界(函式中的最后一條陳述句)時,您的代碼中只有一個小錯誤:
area *= ((rb - lb)/(3 * rb))
而它應該除以段數,所以:
area *= (rb - lb) / (3 * r)
通過這種修改,為輸入值 0、2 和 4 生成的輸出確實是 4.0。
這是對您的代碼的修改,其中我將函式f(x) = x ** 3作為引數,trapezoid以便其他函式可以輕松更改它。我還稍微簡化了while
回圈的主體。
def trapezoid(lb, rb, r, f): # f = function used
width = (rb - lb) / r
currentX = lb
area = f(currentX)
multby4 = True
currentX = width
while currentX < rb:
if multby4:
area = 4 * f(currentX)
else:
area = 2 * f(currentX)
currentX = width
multby4 = not multby4 # switch bit multby4 for the next iteration
area = f(rb)
area *= (rb - lb) / (3 * r)
return area
def f(x):
return x ** 3
lftBount = int(input("Enter the left bound:"))
rgtBount = int(input("Enter the right bound:"))
Repeat = int(input("How many times do you want"))
print(trapezoid(lftBount, rgtBount, Repeat, f))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/337040.html
上一篇:沿圓排列圓而不重疊
