我正在尝试编写一个使用矩形规则计算积分的代码,并允许用户输入积分限制和divions数量(矩形)。我写了这个函数,但对于某些值,它只返回“None”。知道为什么吗?
到目前为止,这是我的代码:
def integral(f, a, b, N):
h = int((b-a)/N)
result = 0
result += h * f(a)
for i in range(1, N-1):
result += h * f(a + i*h)
return result
def f(x):
return x**3
string_input1 = input("Please enter value for a: ")
a = int(string_input1)
string_input2 = input("Please enter value for b: ")
b = int(string_input2)
while True:
string_input3 = input("Please enter integer positive value for N: ")
N = int(string_input3)
if N>0:
break
print(integral(f, a, b, N))
返回“无”的值的示例是a = 0 b = 1 N = 2
答案 0 :(得分:2)
ALTER TRIGGER [dbo].[WORKORDERSCURDATE]
ON [dbo].[WORKORDERS]
AFTER INSERT, UPDATE, DELETE
AS
IF TRIGGER_NESTLEVEL() > 1
RETURN
BEGIN
INSERT INTO WORKORDERS
SELECT *
FROM OPENQUERY([DB29], 'SELECT DISTINCT Customers.CustomerID, Customers.Customer_Bill_Name, Customers.WhichShipVia,
LineItem.ItemID, JrnlHdr.INV_POSOOrderNumber, JrnlHdr.CustomerInvoiceNo,
JrnlHdr.Comment2, JrnlHdr.ShipByDate, JrnlHdr.GoodThruDate, JrnlHdr.CustomerSONo, JrnlHdr.Reference, JrnlHdr.TransactionDate,
JrnlRow.DistNumber, LineItem.SalesDescription, LineItem.PartNumber, LineItem.Category, LineItem.ItemClass, LineItem.ItemDescription
FROM Customers
INNER JOIN JrnlHdr ON Customers.CustomerRecordNumber = JrnlHdr.CustVendId
LEFT OUTER JOIN Address ON Customers.CustomerRecordNumber = Address.CustomerRecordNumber
INNER JOIN JrnlRow ON JrnlHdr.PostOrder = JrnlRow.PostOrder
INNER JOIN LineItem ON JrnlRow.ItemRecordNumber = LineItem.ItemRecordNumber
WHERE JrnlHdr.JrnlKey_Journal = 11
AND JrnlHdr.TransactionDate = CURDATE()
AND JrnlHdr.PostOrder = JrnlRow.PostOrder
AND JrnlHdr.CustVendId = Customers.CustomerRecordNumber
AND JrnlRow.ItemRecordNumber = LineItem.ItemRecordNumber
AND JrnlHdr.POSOisClosed = 0')
end
如果for i in range(1, N-1):
result += h * f(a + i*h)
return result
然后N = 2
将不会执行,那么for i in range(1, 1)
将返回integral
。
但是即使None
,N > 2
循环中有return
也没有任何意义,因为它只会运行第一次迭代,然后返回for
所有的result
答案 1 :(得分:1)
第一个问题是变量h
为int
,然后是循环,直到N-1
,然后是循环内的return
。
def integral(f,a,b,N):
h = float(b-a)/float(N)
result = 0.
result += h*f(a)
for i in range(1,N):
result += h*f(a+i*h)
return result
答案 2 :(得分:0)
你已经有了一个很好的答案,但你的代码可以稍微改进一下:
没有理由将最左边的端点与其他样本点对待。从a = a + 0
开始,如果您使用i=0
启动循环,则会在第一轮循环中选择a
:
def integral(f,a,b,N):
h = (b-a)/float(N)
result = 0.0
for i in range(N):
result += h*f(a+i*h)
return result
此外,通过直接将sum
应用于理解来替换显式循环会更加Pythonic:
def integral(f,a,b,N):
h = (b-a)/float(N)
return h*sum(f(a + i*h) for i in range(N))
这在功能上与第一个定义相同。例如:
>>> integral(lambda x: x**2,0,1,100)
0.32835000000000003
最后,如果您使用的是Python 2,则应更改上述内容,以便使用xrange()
而不是range()
。