python错误:参数必须是字符串或数字,而不是函数

2024-04-20 12:04:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

import numpy as np
import math
x = np.arange(0, 1.1, h) #point in space
t = np.arange(0, 1.1, k) #point in time
#nodes in matrix form
m = len(x)
n = len(t)
T = np.zeros((m,n))

def ft0 (x):
f = lambda x: math.sin(math.pi*x)# Initial Condition at t=0
return f

for i in range (m-1):
   T[0][i] = ft0[i]

当我运行代码时,我得到:

TypeError: float() argument must be a string or a number, not 'function'

我一直在网上寻找解决方案,但我并不真正理解错误


Tags: 代码inimportnumpylentimeasnp
1条回答
网友
1楼 · 发布于 2024-04-20 12:04:13

代码中存在多个问题

  1. hk没有在您提供的代码中定义,我假设它们都是0.1
  2. 正如我在评论中提到的,您应该将函数调用为ft0(i),而不是像您那样
  3. 返回定义的lambda函数而不是结果,因此应将其更改为...return f(x)而不是...return f,这会导致上述错误

您可以在以下代码中看到上述内容:

import numpy as np
import math

def ft0(x):
    f = lambda x: math.sin(math.pi*x)# Initial Condition at t=0
    return f(x)

h=0.1
k=0.1

x = np.arange(0, 1.1, h) #point in space
t = np.arange(0, 1.1, k) #point in time

#nodes in matrix form
#nodes in matrix form
m = len(x)
n = len(t)
T = np.zeros((m,n))

for i in range(m-1):
   T[i][0] = ft0(i)

print(T)

注意

  1. 如果只分配给第一个column,可能应该使用double for循环
  2. 在函数中lambda的情况下,像您所做的那样是不必要的,您可以将lambda用作函数。我建议您在下面的链接https://realpython.com/python-lambda/中阅读有关它的内容

相关问题 更多 >