当另一个值切换符号时重置值

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

我有一个电池恒流充电/放电的数据集。数据如下:

time = np.arange(0,100,1)
current_discharge = [-2 for i in np.arange(0,50,1)]
current_charge = [2 for i in np.arange(50,100,1)]
current = current_discharge + current_charge

我想计算绝对电荷(abs(时间*电流))作为时间的函数。为此,当电流从负切换到正(即 50)时,我需要将电荷重置为零。

在下面的代码中,它会在 50 后从累积费用中减去。相反,我希望累积费用在 50 时为零,然后增加。

cumsum = 0
dQ_list = []
totalcharge = []

for i, t in zip(current,time):
    dQ = -(t+1-t)*i
    dQ_list.append(dQ)
    cumsum += dQ
    totalcharge.append(cumsum)

fig = plt.figure()
ax1 = plt.axes((0,0,1,0.5))
ax1.plot(time,current, label = "current vs time")
ax1.plot(time,totalcharge, label = "charge vs time")
ax1.set_xlabel("Time")

ax1.legend()
python for-loop while-loop reset
1个回答
0
投票

我不确定我是否100%明白,但我认为这就是你所需要的:

charge_started = False  # Flag to track if charge accumulation started

for i, t in zip(current, time):
    dQ = -(t + 1 - t) * i
    dQ_list.append(dQ)
    if i < 0:  # Check if current is negative, while the current retreives
               # from current_discharge, it behaves as it was in your code
        cumsum += dQ
        charge_started = True
    elif charge_started:
        cumsum = 0  # Reset cumsum to 0 when current becomes positive, it goes
                    # here only once
        charge_started = False
    else:
        cumsum += -dQ # all the other current, i put a - because you told you
                      # wanna see the current increase, you can adjust it as 
                      # you wish
    totalcharge.append(cumsum)

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