我无法按照下面的编码顺序完成for循环。我没有看到任何错误,因为我选择NP.WORD(NPUTE)来创建席的一维数组,并且由于某些原因,循环不会填充这些值。p>
def intrpf(xi,x,y):
"""Function to interpolate between data points
using Lagrange polynomial (quadratic)
Inputs
x Vector of x coordinates of data points (3 values)
y Vector of y coordinates of data points (3 values)
xi The x value where interpolation is computed
Output
yi The interpolation polynomial evaluated at xi
"""
#* Calculate yi = p(xi) using Lagrange polynomial
yi = ( (xi-x[1])*(xi-x[2])/((x[0]-x[1])*(x[0]-x[2])) * y[0]
+ (xi-x[0])*(xi-x[2])/((x[1]-x[0])*(x[1]-x[2])) * y[1]
+ (xi-x[0])*(xi-x[1])/((x[2]-x[0])*(x[2]-x[1])) * y[2] )
return yi
#* Initialize the data points to be fit by quadratic
x = np.empty(3)
y = np.empty(3)
print ('Enter data points as x,y pairs (e.g., [1, 2]')
for i in range(3):
temp = np.array(input('Enter data point: '))
x[i] = temp[0]
y[i] = temp[1]
#* Establish the range of interpolation (from x_min to x_max)
xr = np.array(input('Enter range of x values as [x_min, x_max]: '))
我在这一部分陷入了困境,它似乎设置正确,但for循环中的xi[I]上出现了“数组索引太多”的问题。
#* Find yi for the desired interpolation values xi using
# the function intrpf
nplot = 100 # Number of points for interpolation curve
xi = np.empty(nplot)
yi = np.empty(nplot)
for i in range(nplot) :
xi[i] = xr[0] + (xr[1]-xr[0])* i/float(nplot)
yi[i] = intrpf(xi[i], x, y) # Use intrpf function to interpolate
从
np.array
的文档中:这意味着数组应该接收类似列表的内容,以便进行转换,而输入返回字符串。python在一天结束时试图做的是
虽然做这样的事情很有诱惑力
您永远不应该这样做,因为这是不安全的,因为它允许用户在您的程序中执行任何类型的代码。如果你真的需要这种意见,我建议你
数据
<>这个代码甚至没有达到“我选择NP.WORD(NPLE)来创建席的一维数组,并且由于某些原因,循环不会填充这些值。”p>input
行出现错误:请求帮助时,提供有关错误的完整准确信息
如果我将输入行更改为:
通过用户
input
获取数组值并不理想,但这至少是可行的input
(在Py3中)不评估输入;它只返回一个字符串。我将其拆分(使用默认空间),然后将值分配给数组x
被定义为浮点数组,因此x[i]=temp[0]
负责将字符串转换为浮点数组。类似地,xr
行从字符串输入生成浮点数组。这种输入风格不是很稳健;输入错误很容易导致错误===
其余代码使用以下输入运行:
相关问题 更多 >
编程相关推荐