Python中的Newton-Raphson中的TypeError

时间:2019-11-26 08:06:02

标签: python typeerror

我是Python的新手。我正在尝试Newton-Raphson寻根方法。在第4行中,出现错误“发生了异常:TypeError'numpy.float64'对象不可调用”。如果有人可以启发我解决问题,将不胜感激。谢谢。

import numpy as np

def newton(f, df, x, tol=1e-8, max_it=20, it_count = 0):
    x -= f(x)/df(x)
    it_count += 1

    if it_count > max_it:
        raise ValueError("Maximum number of iterations has been exceeded")
    elif abs(f(x)) <= tol:
        return x
    else:
        x = newton(f, df, x)

def f(x):
    return np.tan(x) - 2*x

def df(x):
    d = 0.0000001
    return (f(x+d)-f(x-d))/(2*d)

print(newton(f(1.2), df(1.2), 1.2))

3 个答案:

答案 0 :(得分:2)

在最后一行中,您要处理的是函数和在某个点评估的渐变,而不是函数本身。您可以尝试将最后一行更改为以下内容:

print(newton(f, df, 1.2))

正如Belliger指出的那样,您还应该在递归函数调用中交出迭代计数。此外,您应该在递归中返回该值。这是代码的有效版本:

import numpy as np

def newton(f, df, x, tol=1e-8, max_it=20, it_count = 0):
    x -= f(x)/df(x)
    it_count += 1

    if it_count > max_it:
        raise ValueError("Maximum number of iterations has been exceeded")
    elif abs(f(x)) <= tol:
        return x
    else:
        x = newton(f, df, x, it_count=it_count)
        return x

def f(x):
    return np.tan(x) - 2*x

def df(x):
    d = 0.0000001
    return (f(x+d)-f(x-d))/(2*d)

print(newton(f, df, 1.2))

答案 1 :(得分:0)

其他答案已经回答了您的问题,但我注意到的另一件事是,在应用递归调用时,您需要传递it_count,例如

else:
   x = newton(f, df, x, it_count=it_count)

答案 2 :(得分:0)

# Defining Function
def f(x):
    return x**3 - 5*x - 9

# Defining derivative of function
def g(x):
    return 3*x**2 - 5

# Implementing Newton Raphson Method

def newtonRaphson(x0,e,N):
    print('\n\n*** NEWTON RAPHSON METHOD IMPLEMENTATION ***')
    step = 1
    flag = 1
    condition = True
    while condition:
        if g(x0) == 0.0:
            print('Divide by zero error!')
            break

        x1 = x0 - f(x0)/g(x0)
        print('Iteration-%d, x1 = %0.6f and f(x1) = %0.6f' % (step, x1, f(x1)))
        x0 = x1
        step = step + 1

        if step > N:
            flag = 0
            break

        condition = abs(f(x1)) > e

    if flag==1:
        print('\nRequired root is: %0.8f' % x1)
    else:
        print('\nNot Convergent.')


# Input Section
x0 = input('Enter Guess: ')
e = input('Tolerable Error: ')
N = input('Maximum Step: ')

# Converting x0 and e to float
x0 = float(x0)
e = float(e)

# Converting N to integer
N = int(N)


#Note: You can combine above three section like this
# x0 = float(input('Enter Guess: '))
# e = float(input('Tolerable Error: '))
# N = int(input('Maximum Step: '))

# Starting Newton Raphson Method
newtonRaphson(x0,e,N)

View Code & Output Here

还要检查codesansar.com/numerical-methods/。该站点收集了大量使用C,C ++,Python和MATLAB进行数值方法的算法,伪代码和程序。