Где-то видимо я не доглядел в индексах, не понимаю где.
Получаю: “ index 380 is out of bounds for axis 0 with size 380 ”
это в моменте цикл в цикле U.
U = np.zeros((n, m)) for i in range(0, n): U[1, ] = np.exp(-x[i] / 2) for j in range(0, n-1): for i in range(n, m): U[i+1, j] = (1+c*r)*U[i,j] - c*r*U[i,j-1] + tau*(np.log(1+t[i]) - 2*x[i])
import numpy as np import matplotlib.pyplot as plt import math as ma def solve(): h = 0.001 c = 0.4 T = 1.9 xmin = 0.2 xmax = 2.2 h = 0.01 r = 0.5 tau = r*h n = ma.floor(T/tau) #right bound m = ma.floor((xmax - xmin)/h) + n t = [] for i in range(n): t.append(i*tau) x = np.linspace(xmin, xmax, m) U = np.zeros((n, m)) for i in range(0, n): U[1, ] = np.exp(-x[i] / 2) for j in range(0, n-1): for i in range(n, m): U[i+1, j] = (1+c*r)*U[i,j] - c*r*U[i,j-1] + tau*(np.log(1+t[i]) - 2*x[i]) y = np.ones(len(x)) for i in range(0,n): y[i] = pow((x[i]-2.5*t[i]),2) - t[i] + (1+t[i])*np.log(t[i]+1) + np.exp(-(x[i]-2.5*t[i])/2) - pow(x[i],2) plt.plot(x, U[:,i]) plt.plot(x, y) #plt.xlim(xmin, xmax) #plt.ylim(0, T) plt.show() solve()
вот, например, та же самая задача на R, работает. Я хочу упростить немного, переписав на python, поэтому код не 1 в 1 копировал, но по идее суть остается одна.
require(ggplot2) Solve = function(h, r){ if(r > 1) return("��� r > 1 ����� ����������") if(r <= 0) return("r ������ ���� ������ 0") phiFunc = function(x, t){ #return(x^2/2 + 2*t) return(x^2/2 + 2*t) exp(-x/2) } psi = function(x){ #return(1 + cos(x)) return(exp(-x/2)) } u_an = function(x, t){ #return((x^3)/6 - ((x-t)^3)/6 + t^2 + cos(x-t) + 1) return((x-2.5*t)^2 - t + (1+t)*log(1+t) + exp(-(x-2.5*t)/2) - (x^2)) } # a = -1 # b = 1 # c = -1 # T = 2 a = 0.2 b = 2.2 c = -0.4 T = 1.9 #r = 1 #h = 0.01 tau = r * h #up bound N = floor(T/tau) #right bound M = floor((b - a)/h) + N x = seq(from = b - M*h, length.out = M, by = h) u = matrix(0, N, M) u[1, ] = sapply(x, psi) for(n in 1:(N - 1)){ phi = sapply(x, function(x){ return(phiFunc(x, tau * (n-1))) }) for(m in (n + 1):M){ u[n + 1, m] = tau * phi[m] + u[n, m] + c*r*(u[n, m] - u[n, m-1]) } if(n%%100 == 0) { print(sprintf("%.2f%%", 100*n/N)) } } df = data.frame(x = x[(N+1):M], u1 = u[ 1, (N+1):M], u2 = u[ N/3, (N+1):M], u3 = u[2*N/3, (N+1):M], u4 = u[ N-1, (N+1):M], u_an1 = sapply(x, function(x) u_an(x, 0) ) [(N+1):M], u_an2 = sapply(x, function(x) u_an(x, T/3) ) [(N+1):M], u_an3 = sapply(x, function(x) u_an(x, 2*T/3)) [(N+1):M], u_an4 = sapply(x, function(x) u_an(x, T) ) [(N+1):M] ) g = ggplot(df, aes(x)) + geom_line(aes(y = u1)) + geom_line(aes(y = u_an1), col = 2) print(g) g = ggplot(df, aes(x)) + geom_line(aes(y = u2)) + geom_line(aes(y = u_an2), col = 2) print(g) g = ggplot(df, aes(x)) + geom_line(aes(y = u3)) + geom_line(aes(y = u_an3), col = 2) print(g) g = ggplot(df, aes(x)) + geom_line(aes(y = u4)) + geom_line(aes(y = u_an4), col = 2) print(g) print("100%") } Solve(0.01, 0.5)