热方程图:索引错误:只有整数、切片(`:`)、省略号(`...`)、numpy.newaxis(`None`)和整数或布尔数组是有效索引[重复]

tmb3ates  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(129)

此问题已在此处有答案

only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices(3个答案)
上个月关门了。
我从这里得到代码:
Solving heat equation with python (NumPy)
但是我在运行这个的时候得到一个错误:

# solve the heat equation for a metal rod as one end is kept at 100 °C 
# and the other at 0 °C 
# u(0,t) = 100 (x=0)
# u(L,t) = 0 (x=L)

import numpy as np
import matplotlib.pyplot as plt

dt = 0.0005
dy = 0.0005
k = 10**(-4)
y_max = 0.04
t_max = 1
T0 = 100

def FTCS(dt,dy,t_max,y_max,k,T0):
    s = k*dt/dy**2
    y = np.arange(0,y_max+dy,dy) 
    t = np.arange(0,t_max+dt,dt)
    r = len(t)
    c = len(y)
    T = np.zeros([r,c])
    T[:,0] = T0
    for n in range(0,r-1):
        for j in range(1,c-1):
            T[n+1,j] = T[n,j] + s*(T[n,j-1] - 2*T[n,j] + T[n,j+1]) 
    return y,T,r,s

y,T,r,s = FTCS(dt,dy,t_max,y_max,k,T0)

plot_times = np.arange(0.01,1.0,0.01)
for t in plot_times:
    plt.plot(y,T[t/dt,:])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[36], line 25
     23 plot_times = np.arange(0.01,1.0,0.01)
     24 for t in plot_times:
---> 25     plt.plot(y,T[t/dt,:])

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

如何解决这一问题?

mgdq6dx1

mgdq6dx11#

在绘图时,T的索引是float值,因此将t/dt转换为int将修复索引问题。

plot_times = np.arange(0.01,1.0,0.01)
for t in plot_times:
    plt.plot(y,T[int(t/dt),:])

相关问题