【发布时间】:2020-04-15 01:11:26
【问题描述】:
我正在尝试编写一个脚本,该脚本使用前向、后向和居中近似值计算数值导数,并绘制结果。我用 100 个点制作了一个从 0 到 2pi 的 linspace。我过去做过很多数组和 linspaces,但我从未见过这个错误:“ValueError: sequence too large; cannot be greater than 32”
我不明白问题出在哪里。这是我的脚本:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.cos(x) + np.sin(x)
def f_diff(x):
return np.cos(x) - np.sin(x)
def forward(x,h): #forward approximation
return (f(x+h)-f(x))/h
def backward(x,h): #backward approximation
return (f(x)-f(x-h))/h
def center(x,h): #center approximation
return (f(x+h)-f(x-h))/(2*h)
x0 = 0
x = np.linspace(0,2*np.pi,100)
forward_result = np.zeros(x)
backward_result = np.zeros(x)
center_result = np.zeros(x)
true_result = np.zeros(x)
for i in range(x):
forward_result[i] = forward[x0,i]
true_result[i] = f_diff[x0]
print('Forward (x0={}) = {}'.format(x0,forward(x0,x)))
#print('Backward (x0={}) = {}'.format(x0,backward(x0,dx)))
#print('Center (x0={}) = {}'.format(x0,center(x0,dx)))
plt.figure()
plt.plot(x, f)
plt.plot(x,f_diff)
plt.plot(x, abs(forward_result-true_result),label='Forward difference')
我确实尝试将 linspace 点设置为 32,但这给了我另一个错误:“TypeError: 'numpy.float64' 对象不能被解释为整数” 那个我也看不懂。我做错了什么?
【问题讨论】:
标签: python-3.x sequence typeerror valueerror derivative