python梯形面积,Python中的梯形和辛普森规则?

博主在使用Python实现梯形法则和辛普森法则计算e^(-x^2)的积分时,发现答案与老师给出的不符。问题在于原函数可能被误解为e^((-x)^2),实际上应该是e^(-x^2)。修正函数后,正确答案为1.77251356。
摘要由CSDN通过智能技术生成

I have to write the trapezoid and simpson rule in python for the function e^((-x)^2).

Here's what I got so far. The answer it gives out is 8218.7167913 but the answer according to my teacher is something like 1.77251356.....

Where did I go wrong?

from numpy import *

def f(x):

return e**((-x)**2)

def trapezoid(f, a, b, n):

deltax = float(b - a)/(n)

h = float(b - a) / n

s = 0.0

s += f(a)/2.0

for i in range(1, n):

s += f(a + i*h)

s += f(b)/2.0

return s * h

print trapezoid(f, -3, 3, 6)

解决方案

Look at your function: e^((-x)^2). The negative sign isn't doing anything because you're squaring it away immediately. That seems strange. More likely is that you were supposed to integrate e^(-x^2). Let's test:

>>> trapezoid(lambda x: e**((-x)**2), -3, 3, 1000)

2889.3819494560144

>>> trapezoid(lambda x: e**(-x**2), -3, 3, 1000)

1.7724146920763713

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值