在Python中,如何在函数中定义任意数量的索引变量?



首先,提前感谢您对我初学者对Python的理解。我是从MATLAB来的,希望这能给你一些背景。

在MATLAB中,我定义了一个数学函数:
f =@ (x) 2*x(1)^2 + 4*x(2)^3

在Python中,我写:

def f(x):
return 2*x(1)**2 + 4*x(2)**3

但我得到一个错误在我的其他函数(有限差分方法创建梯度向量):

line 9, in f
return 2*x(1)**2 + 4*x(2)**3
TypeError: 'numpy.ndarray' object is not callable

(一个包含n个条目的输入X1,由原方程中变量的个数指定,被反馈到函数f(x)中,在特定点求值)

更新2021-10-22下面我包含了供参考的代码。此代码当前有效。

我想知道的主要事情是我如何创建一个方程的任意数量的变量,就像我在MATLAB中做x(1),x(2)…x(n)。我被告知我应该使用def f(*x),但当我在f(x)上添加'*'运算符时,我得到tuple index out of range错误。

import math, numpy as np
def gradFD(var_init,fun,hx):
df = np.zeros((len(var_init),1)) #create column vector for gradient output

# Loops each dimension of the objective function
for i in range(0,len(var_init)):
x1 = np.zeros(len(var_init)) #initialize x1 vector
x2 = np.zeros(len(var_init))
x1[i] = var_init[i] - hx
x2[i] = var_init[i] + hx
z1 = fun(x1)
z2 = fun(x2)
# Calculate Slope
df[[i],[0]] = (z2 - z1)/(2*hx)


# Outputs:
c = df #gradient column vector
return c

测试脚本:

import math
import numpy as np
from gradFD import gradFD
def f(x):
return 2*x[0]**2 + 4*x[1]**3 #THIS IS THE NOW WORKING CODE
#return 2*x**2 + 4*y**3
var_init = [1,1] #point to evaluate equation at
c = gradFD(var_init,f,1e-3)
print(c)

Python中的数组索引是用方括号完成的,而不是圆括号。记住Python的下标从0开始,而不是1。

def f(x):
return  2*x[0]**2 + 4*x[1]**3

您的函数被称为f,但您正在尝试调用x(2)。你得到错误,因为你试图调用x作为一个函数,但x是一个numpy数组

最新更新