在python +故障排除中使用polyfit的牛顿方法

时间:2018-03-01 16:48:11

标签: python numpy tuples

所以我试图使用牛顿方法来找到复杂函数的根。这是我目前的代码:

import numpy

xvals = numpy.arange(-5, 5)
def g():
    return numpy.random.random(1) + numpy.random.random(1) *1j
p= numpy.poly1d(numpy.squeeze([g(),g(),g()]))  # test function p
q = numpy.poly1d(numpy.squeeze([g(),g(),g()])) #test function q
f = p/q
pprime = numpy.polyder(p)
qprime = numpy.polyder(q)
print("compare", + numpy.roots(p)) #compare our function to this

def newton(x,tolerance = .000001): #newton method
    x1=1
    x=0
    while (True):
        x1 = numpy.subtract(x, - (1/((pprime/p) - (qprime/q))))
        t = abs(x1 - x)
        if t < tolerance:
            break
    x = x1
    return x
print(newton(1))    
def polyzeros(a): 
    coeff = numpy.polyfit(x,p(x),1) #Returns a vector of coefficients p that minimises the squared error.
    zeros = numpy.polyfit(x,prime(x),1)
    return zeros
print("our answer",+polyzeros(3))

发生了几个不同的错误

16     x=0
     17     while (True):
---> 18         x1 = numpy.diff([x, - (1/((pprime/p) - (qprime/q)))])
     19         t = abs(x1 - x)
     20         if t < tolerance:
TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple' 

在这种情况下,我尝试了几个不同的东西,比如使用numpy.sub或numpy.diff和zip,正如其他人在stackoverflow上所建议的那样,但无济于事。还有其他想法吗?

0 个答案:

没有答案