蟒蛇中的牛顿拉夫森

时间:2017-04-24 09:17:55

标签: function scipy newtons-method

我想找到给定参数a,b,c的简单函数的零。我必须使用牛顿拉夫森方法。我编译代码时遇到的问题是没有定义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'未定义"

任何人都知道为什么会这样?先谢谢

伯纳特

2 个答案:

答案 0 :(得分:0)

大多数编程语言的工作方式是它们使用变量(代码中的名称a,b,c,u)和函数(例如,零)。

在调用函数时,Python期望定义所有输入的“数量”。在您的情况下,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))

答案 1 :(得分:0)


#####Crude way of doing it to see what's going on! 
####Newton Rhapson

###Define Function
def f(x):
    return x ** 6 / 6 - 3 * x ** 4 - 2 * x ** 3 / 3 + 27 * x ** 2 / 2 \
        + 18 * x - 30

###Define Differential
def d_f(x):
    return x ** 5 - 12 * x ** 3 - 2 * x ** 2 + 27 * x + 18


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)"])
df
col = list(df.columns)



df
相关问题