Python错误:"';浮动';对象不可下标";
我正在使用一位教授给我的一些代码,但我不知道该怎么做。 我得到一个错误:Python错误:"';浮动';对象不可下标";,python,Python,我正在使用一位教授给我的一些代码,但我不知道该怎么做。 我得到一个错误: 26 err=(x0-2.) ---> 27 rate_est=abs(err[1:-1]/err[0:-2]) 28 print('The estimate of our convergence rate is:', rate_est) TypeError: 'float' object is not subscriptable 如果对您有用,以下是其他相关代码: import matplotlib.
26 err=(x0-2.)
---> 27 rate_est=abs(err[1:-1]/err[0:-2])
28 print('The estimate of our convergence rate is:', rate_est)
TypeError: 'float' object is not subscriptable
如果对您有用,以下是其他相关代码:
import matplotlib.pyplot as plt
import numpy as np
def g(S,x):
g=(1/2)*((S/x)+x)
return g;
x0=1
S=2
tol=pow(10.0,-10)
stopCrit=1.0
deltaX=1.0
nIter=0
xn=x0
print(x0)
while((stopCrit>tol) and (nIter<50)):
nIter=nIter+1
x1=g(S,x0)
xn=np.append(xn,x1)
print(x1)
deltaX=np.abs(x1-x0)
stopCrit=deltaX/np.abs(x1)
x0=x1
xn=np.array(xn)
err=(x0-2.)
rate_est=abs(err[1:-1]/err[0:-2])
print('The estimate of our convergence rate is:', rate_est)
导入matplotlib.pyplot作为plt
将numpy作为np导入
def g(S,x):
g=(1/2)*((S/x)+x)
返回g;
x0=1
S=2
tol=功率(10.0,-10)
stopCrit=1.0
deltaX=1.0
硝酸盐=0
xn=x0
打印(x0)
而((stopCrit>tol)和(nIter你的err=(x0-2.)
是一个浮点数。在下面的语句中,你把它当作一个列表或元组或其他东西:err[1:-1]/err[0:-2]
,这没有任何意义。你不能索引到浮点数中。你可能想索引到数组中。xn
看起来像一个(唯一的?)数组,因此您可能希望改为执行err=(xn-2.)
,但如果不理解您要执行的操作,很难说。变量和函数名应在小写字母后面加下划线。缺少空格是否意味着要惩罚读卡器的错误?