以只有一些特定的值存储“而”循环中

问题描述 投票:0回答:2

我解决一些偏微分方程离散的时间和空间,以避免复杂我避免这件事情,只是认为我使用一个功能,我所谓的“计算”,在迭代的方式解决问题。问题的关键是,我想借此(和存储在一些矩阵称为“CN”)的循环“而”的“Y”给予一定的价值,但没有采取迭代的所有值的时间。

准确地说:我做了服用一段时间陡峭DT时间演化的循环“而”。我从t = 1乳宁它使用DT = 0.001到t = 100。我的解决方案“Y”被计算为每次陡峭。问题的关键是,我想要存储的“Y”的时间“t”一些特定的值,而不是在循环的每次陡,即比如我想要存储的值在t = 1.0,2.0,3.0 ,. ..,100.0使用我的循环,而内部计算值。但我不希望存储的“Y”的值在t = 1.001,1.002,1.003等

我告诉你,我做的代码

import numpy as np
import math
from matplotlib import pyplot as plt
import matplotlib.animation as animation



# grid in 1D
xmin = 0.0
xmax = 100.0
Nx = 120
dx = (xmax-xmin)/Nx
x = np.linspace(xmin,xmax,Nx)
# timing of the numerical simulation
t_initial = 1.0
t_final = 100.0
t = t_initial
dt = 10**(-2)
#initial profile
y = np.exp(-0.5*x**2)
#number of time points to store the numerical solution
dt_solution = 1.0 #time steep to save the numerical data inside the loop while
Nt = int((t_final-t_initial)/dt_solution)




def computation(t,y):
    return np.log(t)+y




Cn = np.zeros((Nt, len(x))) # holds the numerical solution
Cn[0,:] = y #we put the initial y
ite = 0
while t<t_final:


    t += dt #WE MAKE THE TIME STEEP
    ite +=1

    y = computation(t,y)

    #Cn[ite,:] = y #I WANT TO SAVE THE VECTOR Y FOR THE TIMES t THAT I AM INTERESTD, NOT THE ONES GIVEN INSIDE THE LOOP WHILE

有人知道如何做到这一点?我想也许解决使用两个循环这个问题,但我想知道,如果它可以使用一些更有效的方式。谢谢! (我希望我的问题是清楚的,如果不是请告诉我)

python loops
2个回答
1
投票

你可以使用一个modulo operator。该运营商表示,当一个数除以另一个余数。例如:

10%2 = 0 # 10 is exactly divisible by 2  
11%2 = 1 # 11 is divisible by 2 with remainder 1

我们可以用while环路内的,如果使用这个方法。

#...

t = 0
dt=0.001 #timestep for iteration

# set the condition threshold
threshold = dt/10
# choose the step you want to save values at
store_step = 0.1

while t<100:
    t += dt
    y = computation(t,y)
    if (t%store_step<threshold) or (t%store_step>(store_step-threshold)):
       # store y values
       Cn[ite,:] = y

注意:如果你的时间步,你可以使用一个整数:if (t%1==0)为您的病情。


0
投票

这种添加到您想要保存whiley循环:

if int(t % 1) == 0:
    Cn[ite,:] = y

因此,这不仅节省了yt1整除,即t1.000, 2.000...

同样,如果你有要在其中仅保存y在其他条件下,只需核对在可以计算的方式,条件。如果不是,静态listset是一个可行的选择也是如此。

© www.soinside.com 2019 - 2024. All rights reserved.