首页 > 解决方案 > Python Gaussian Quadrature 和梯形规则积分误差

问题描述

问题详情

一直在尝试做这条蟒蛇。问题详情在图片链接中

运行程序时出现此错误

任何帮助表示赞赏

   File "C:/Users/User/Desktop/Python/tapez.py", line 9, in exactIntegral
     integral = ((4(math.cos(0.4*b)** 2)) * ((5(math.exp( -0.5 * b))) +

 TypeError: 'int' object is not callable

这是代码

import math
import numpy
import scipy.integrate.quadrature as quad

def fun(x):
    return x*numpy.sin(x)

def exactIntegral(a, b):
    integral = (((9)+4(math.cos(0.4*b)** 2)) * ((5(math.exp( -0.5 * b))) +
                 (2(math.exp( 0.15 * b)))))+ (((9)+4(math.cos(0.4*a)** 2)) * 
                ((5(math.exp( -0.5 * a))) + (2(math.exp( 0.15 * a)))))

    return integral

a = 0.0
b = 8.0

exact = exactIntegral(a, b)
estimate = quad(fun,a,b)
print("Gaussian Quadrature: ", exact)

# Trapazoid Rule
n = 100
h = (b-a)/(n-1)
x = numpy.linspace(a,b,num=n)
area = 0
for i in range(n-1):
    area = area + h*(fun(x[i]) + fun(x[i+1]))/2.0
print("Trapazoid rule: ", area)

标签: python

解决方案


你的问题在这里:

integral = (((9)+4(math.cos(0.4*b)** 2)) * ((5(math.exp( -0.5 * b))) +
                 (2(math.exp( 0.15 * b)))))+ (((9)+4(math.cos(0.4*a)** 2)) * 
                ((5(math.exp( -0.5 * a))) + (2(math.exp( 0.15 * a))))

Python 不会自动解释之类2(x+1)的东西2*(x+1)。您需要*明确指定乘法运算符。

对于 Python2()来说,是一个名为2. 但是2是一个 int 对象,不能像函数一样调用


推荐阅读