python+中使用polyfit的Newton方法

2024-06-25 23:39:39 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着用牛顿法来求复函数的根。这是我目前的代码:

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公司或者微小差异其他人在stackoverflow上建议的压缩,但没有用。还有其他想法吗?你知道吗


Tags: testnumpyreturndeffunctionnewtonrandomtolerance