放射性衰变模拟的Python代码给我一个错误,我不知道如何解决

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

我的代码

import numpy as np
import matplotlib.pyplot as plt

#defining some parameters
N_0 = 10000  #intial number of radioactive atoms
p = 0.04  #decay probability per second
t = 1000  #total time 

#function to simulate radioactive decay
def radioactive_decay_simulation(N_0, p, t):
    time_step = np.arange(0, t + 1, 1)  # Time steps in seconds
    N = np.zeros_like(time_step)  #zero array for number of radioactive atoms decaying as a function of t 
    D = np.zeros_like(time_step)  #zero array for number of daughter radioactive atoms decaying as a function of t
    N[0] = N_0  #assinging initial number of radioactive atoms as the first element of the zero array for N
    p_decay = 1 - np.exp(-p)  #decay probability per time-step
    #loop to model decay of random number of radioactive atoms at each time-step
    for i in range(1, len(time_step)):
        decayed = np.random.rand(N[i - 1]) < p_decay
        N[i] = N[i - 1] - np.sum(decayed)
        D[i] = D[i - 1] + np.sum(decayed)
        #estimateing the half-life when N has decreased to half of its initial value
        if N[i] <= 0.5 * N_0:
            half_life_estimate = time_step[i]
            break
    return time_step, N, D, half_life_estimate

#defining theoretical half-life value 
t_half = np.log(2) / p
#running the simulation
time_step, N, D= radioactive_decay_simulation(N_0, p, t)

#plotting the graphs
plt.figure()
plt.plot(time_step, N, label='Radioactive Parent Atoms')
plt.plot(time_step, D, label='Radioactive Daughter Atoms')
plt.xlabel('Time / s')
plt.ylabel('Number of Radioactive Atoms')
plt.legend()
plt.title('Radioactive Decay Simulation')
plt.show()

#printing half-life estimate and theoretical value for half-life 
print(f"Estimated half-life is {half_life_estimate}")
print(f"Acutal half-life is {t_half}")

我的错误,

ValueError                                Traceback (most recent call last)
Cell In[28], line 63
     57 t_half = np.log(2) / p
     61 #running the simulation
---> 63 time_step, N, D = radioactive_decay_simulation(N_0, p, t)
     66 #plotting the graphs
     68 plt.plot(time_step, N, label='Radioactive Parent Atoms')

ValueError: too many values to unpack (expected 3)

如何修复错误?

python physics
1个回答
0
投票

正如人们所指出的,你的函数返回 4 个值,但你的代码编写时只期望返回 3 个值:

#defining theoretical half-life value 
t_half = np.log(2) / p
#running the simulation
time_step, N, D= radioactive_decay_simulation(N_0, p, t)

您期望返回

time_step, N, D
但您的函数
radioactive_decay_simulation
返回
time_step, N, D, half_life_estimate

我想一个简单的解决方案是更改代码行以期望所有返回值,例如:

time_step, N, D, half_life_estimate = radioactive_decay_simulation(N_0, p, t)
© www.soinside.com 2019 - 2024. All rights reserved.