如何将运算符设置为for循环中的函数?

2024-04-25 12:13:27 发布

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

我想使用一个递归公式,如x(I+1)=x(I)+h 我怎样才能在for循环中输入它,同时找到与之对应的y值并将其分配到一个数组中。我试过了

for i in range(n):
    i+1 = y(i) + h 
    dydx[i] = (y[i+1]+y[i-1]-y[i])/h**2
    dydx0 = [dydx[0]]
    print(dydx0)

这显然给了我一个错误,但我想不出如何做这另一种方式。有人能帮忙吗?你知道吗

def f(x):
    return cos(pi*exp(-x))
    h = 0.01
    x = linspace(a,b,n+1)
    print(x)
    y = f(x)
    dydx = zeros(n+1)

for i in range(n):

    dydx[i] = (y[i+1]+y[i-1]-y[i])/h**2
    dydx0 = [dydx[0]]
    print(dydx0)

在dydx公式中,当我计算dydx[I]=(y[I+1]+y[I-1]-y[I])/h**2时,我想计算y(x+h)+y(x-h)-y(x)/h,但使用I作为x[I+1]=x[I]+h。因此,例如y[I+1]应该是在x[I+1]处计算y的平均值,它本身依赖于h。。你知道吗


Tags: inforreturndef错误方式pirange
1条回答
网友
1楼 · 发布于 2024-04-25 12:13:27

你好像对Python很陌生!有几个语法模式可以帮助你:

  1. return键将结束一个函数,因此函数f()中return关键字下面的任何代码都无法工作。

  2. 等号的左侧应该是要赋值/修改的变量。在python中:

    i+1=y(i)+h

    左边是“add1 to i”,右边是“add h to the result of the function y when given parameter i”。这是各种各样的错误。

如果你的目标是

[using] the recursion formula as x(i+1) = x(i) +h How can I input that in the for loop but also find the y- values corresponding to this and allocate it into an array.

您的代码看起来更像这样:

values_of_x = []
values_of_y = []
initial_x = 10
number_of_recursions = 100 


values_of_x.append(initial_x)
values_of_y.append(y(initial_x))


for i in range(number_of_recursions):
    current_x = values_of_x[-1]
    next_x = current_x + h
    next_y = y(next_x)
    values_of_x.append(next_x)
    values_of_y.append(next_y)

print('Values of x displayed below:')
print(values_of_x)
print('Values of y displayed below:')
print(values_of_y)

这假设您已经定义了一个函数y(),该函数接受x的值并返回一个值,不过从示例代码来看,您可能正在执行比这更复杂的操作!你知道吗

相关问题 更多 >