python - 得到一个:“TypeError:'numpy.float64'对象不可调用”与贝塞尔函数相关的程序错误
问题描述
该计划的目的是:
“编写一个 python 函数J(m,x),它使用梯形规则计算Jm(x)的值,N = 10000。在程序中使用你的函数来绘制 Bessel 函数J0(x)、J1的图(x) 和 J2(x)作为从x = 0到x = 20的x的函数。”
Jm(x) = (1/pi) 。从 0 积分 [cos(m.theta - x.sin(theta))] --> pi
并且是第一年物理学位的 Python 模块介绍的一部分。
类型错误源自的行来自我的函数,以使用梯形规则集成函数:
def integrate(f, a, b, N:int):
h = (b-a) / N
s = 0
for i in range(1,N):
c = f(a + i*h)
s = s + c
Area = h*(0.5*f(a) + 0.5*f(b) + s)
return Area
错误指的是“c = f(a + i*h)”行:“TypeError: 'numpy.float64' object is not callable”。
鉴于此功能在我制作的其他程序中有效,我不确定此错误的根源是什么。我知道 scipy.integrate.quad 可以更好地进行集成,但是我们被要求不要使用它来演示学习不同的技术。
一种可能性是问题是由较大程序的其他部分引起的。作为一个对一般编程非常陌生的人,似乎可能存在我尚未遇到的其他问题,因为程序在出现错误之前没有解决这些问题。其余代码如下:
import numpy as np
#Defining how to integrate a function using the trapezium rule
def integrate(f, a, b, N:int):
h = (b-a) / N
s = 0
for i in range(1,N):
c = f(a + i*h)
s = s + c
Area = h*(0.5*f(a) + 0.5*f(b) + s)
return Area
def func(o, m, x):
return np.cos(m*o - x*np.sin(o)) #1st attempt at defining the bessel function
def J(m,x):
return (1 / np.pi) * integrate(func(0, m, x), 0, np.pi, 10000)
#Produce range of x-values from 0 to 20.
xvals = np.linspace(0,20,200)
#Calculating the value of the bessel function for each value of x and m
for i in range(200):
for j in range(3):
bessel = J(j, xvals[i])
print("x: {}, m: {}, Val: {}".format(xvals[i], j, bessel)) #Print statement to check the program is functioning correctly before moving on to the next stage
解决方案
return (1 / np.pi) * integrate(func(0, m, x), 0, np.pi, 10000)
在您的函数J
中,您将函数调用作为参数,即它的返回值。更改func(0, m, x)
为func
它应该可以工作。
编辑:
正确的答案是传递一个 lambda 表达式:lambda i: func(i, m, x)
. 归功于 Barmar。
推荐阅读
- java - 无法访问主类中的方法
- vba - Powerpoint VBA - .Tags.Add 上的语法错误
- azure-data-factory - 针对 ADFv2 中的硬编码数组执行 ForEach 活动
- javascript - JS - 对象属性不采用分配的值,但只获取数组的最后一个值
- python-3.x - 将代码块翻译成列表理解语法
- django - Django 无限滚动搞砸了设计。CSS 需要修正
- r - 如何使用 lapply(seq_along()) 保留列表元素的名称?
- wpf - 选择单选按钮组项目时,WPF 菜单不会关闭
- flutter - ListView 中的颤动边框更改移动下面的项目
- python - jupyter notebook 的当前工作目录设置为 vscode 中的临时文件夹