为什么在尝试实施 Newton-Raphson 方法时 "name 'x' not defined"?
Why is "name 'x' not defined" when trying to implement the Newton-Raphson method?
我想找到给定参数 a、b、c 的简单函数的零点。我必须使用 Newton-Raphson 方法。我在编译代码时遇到的问题是 x
变量未定义。
from scipy import optimize
def Zeros(a, b, c, u):
return optimize.newton(a*x**2+b*x+c, u, 2*ax+b, args=(a, b, c))
a,b,c是函数f的常量,u是起点。所以有了这个函数,我应该能够通过指定 a、b、c 和 u 来获得零。例如:
print Zeros(1, -1, 0, 0.8)
但我得到“全局名称 'x' 未定义”。
为什么会这样?
大多数编程语言的工作方式是它们使用变量(代码中的名称 a、b、c、u)和函数(例如 Zeros)。
调用函数时,Python 期望定义所有输入的 "quantities"。在您的情况下,x 不存在。
解决方法是定义一个依赖于x的函数,对于函数及其导数
from scipy import optimize
def Zeros(a,b,c,u):
def f(x, a, b, c):
return a*x**2+b*x+c
def fprime(x, a, b, c):
return 2*a*x + b
return optimize.newton(f, u, fprime=fprime,args=(a,b,c))
print(Zeros(1,-1,0,0.8))
查看发生了什么的粗略方式!
定义函数:
def f(x):
return x ** 6 / 6 - 3 * x ** 4 - 2 * x ** 3 / 3 + 27 * x ** 2 / 2 \
+ 18 * x - 30
定义差异:
def d_f(x):
return x ** 5 - 12 * x ** 3 - 2 * x ** 2 + 27 * x + 18
Newton-Raphson:
x = 1
d = {'x': [x], 'f(x)': [f(x)], "f'(x)": [d_f(x)]}
for i in range(0, 40):
x = x - f(x) / d_f(x)
d['x'].append(x)
d['f(x)'].append(f(x))
d["f'(x)"].append(d_f(x))
df = pd.DataFrame(d, columns=['x', 'f(x)', "f'(x)"])
print(df)
我想找到给定参数 a、b、c 的简单函数的零点。我必须使用 Newton-Raphson 方法。我在编译代码时遇到的问题是 x
变量未定义。
from scipy import optimize
def Zeros(a, b, c, u):
return optimize.newton(a*x**2+b*x+c, u, 2*ax+b, args=(a, b, c))
a,b,c是函数f的常量,u是起点。所以有了这个函数,我应该能够通过指定 a、b、c 和 u 来获得零。例如:
print Zeros(1, -1, 0, 0.8)
但我得到“全局名称 'x' 未定义”。
为什么会这样?
大多数编程语言的工作方式是它们使用变量(代码中的名称 a、b、c、u)和函数(例如 Zeros)。
调用函数时,Python 期望定义所有输入的 "quantities"。在您的情况下,x 不存在。
解决方法是定义一个依赖于x的函数,对于函数及其导数
from scipy import optimize
def Zeros(a,b,c,u):
def f(x, a, b, c):
return a*x**2+b*x+c
def fprime(x, a, b, c):
return 2*a*x + b
return optimize.newton(f, u, fprime=fprime,args=(a,b,c))
print(Zeros(1,-1,0,0.8))
查看发生了什么的粗略方式!
定义函数:
def f(x):
return x ** 6 / 6 - 3 * x ** 4 - 2 * x ** 3 / 3 + 27 * x ** 2 / 2 \
+ 18 * x - 30
定义差异:
def d_f(x):
return x ** 5 - 12 * x ** 3 - 2 * x ** 2 + 27 * x + 18
Newton-Raphson:
x = 1
d = {'x': [x], 'f(x)': [f(x)], "f'(x)": [d_f(x)]}
for i in range(0, 40):
x = x - f(x) / d_f(x)
d['x'].append(x)
d['f(x)'].append(f(x))
d["f'(x)"].append(d_f(x))
df = pd.DataFrame(d, columns=['x', 'f(x)', "f'(x)"])
print(df)