尝试创建一个小脚本来测试名为polyRoots的脚本的不同部分。当我尝试使用缩小的多边形函数时,出现错误。他们对此代码并不复杂,我不确定为什么它不起作用。
import polyRoots as pr
print( "Deflation of polynomial: ")
print( pr.polyRoots.deflPoly( [20, -36, 7, 3], -5 ))
我收到以下错误:
File "C:temp.py", line 13, in <module>
print( pr.polyRoots.deflPoly( [20, -36, 7, 3], -5 ))
AttributeError: 'function' object has no attribute 'deflPoly'
polyRoots脚本是从数值方法到工程设计的书籍代码资源。如下:
## module polyRoots
''' roots = polyRoots(a).
Uses Laguerre's method to compute all the roots of
a[0] + a[1]*x + a[2]*x^2 +...+ a[n]*x^n = 0.
The roots are returned in the array 'roots',
'''
from evalPoly import *
import numpy as np
import cmath
from random import random
def polyRoots(a,tol=1.0e-12):
def laguerre(a,tol):
x = random() # Starting value (random number)
n = len(a) - 1
for i in range(30):
p,dp,ddp = evalPoly(a,x)
if abs(p) < tol: return x
g = dp/p
h = g*g - ddp/p
f = cmath.sqrt((n - 1)*(n*h - g*g))
if abs(g + f) > abs(g - f): dx = n/(g + f)
else: dx = n/(g - f)
x = x - dx
if abs(dx) < tol: return x
print('Too many iterations')
def deflPoly(a,root): # Deflates a polynomial
n = len(a)-1
b = [(0.0 + 0.0j)]*n
b[n-1] = a[n]
for i in range(n-2,-1,-1):
b[i] = a[i+1] + root*b[i+1]
return b
n = len(a) - 1
roots = np.zeros((n),dtype=complex)
for i in range(n):
x = laguerre(a,tol)
if abs(x.imag) < tol: x = x.real
roots[i] = x
a = deflPoly(a,x)
return roots
不确定导致此错误的原因,因为对于每个放气请求来说,它实际上只是一行代码。请指教。
我认为他不能在函数deflPoly
外部调用该函数。因为它是local
范围。
例如:
def a():
print 'a function'
def b():
print 'b function'
a().b()
这应该是错误的,因为函数a()
返回None,即使函数的某个值a()
返回,也没有attribute b
。
为了使用功能b()
,我们必须设置一个link
内部功能如
def a():
print 'a function'
def b():
print 'b function'
return b
test = a()
test()
>>>a function
>>>b function
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句