Python中的梯形和辛普森规则? [英] Trapezoid and Simpson rule in Python?
本文介绍了Python中的梯形和辛普森规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须在python中为函数e^((-x)^2)
编写梯形和辛普森规则.
I have to write the trapezoid and simpson rule in python for the function e^((-x)^2)
.
这是我到目前为止所得到的.它给出的答案是8218.7167913
,但是根据我的老师的回答是类似1.77251356....
的东西.
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....
.
我哪里出错了?
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)
推荐答案
查看您的函数:e^((-x)^2)
.负号没有做任何事情,因为您要立即将其除掉.好像很奇怪您更有可能应该集成e^(-x^2)
.让我们测试一下:
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
这篇关于Python中的梯形和辛普森规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文