如何使用append将循环中的计算值放入数组

2024-10-01 13:26:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在解决一个问题,我的最终目标是得到进动数组中的进动值。这些值是时间与θ图的斜率。我用线性拟合得到了那张图的斜率。我尝试使用append将该斜率放入数组中。这是在为不同的a值执行的函数中

但是进动值数组的长度是131,应该只有24。运行代码时,代码正在为每个a值打印正确的斜率(也就是进动值),但是数组太长了,我不知道这些值是从哪里来的

我怀疑这是我使用append/将斜率值放入空数组的方式。我可以做些什么来获取数组中所需的值

基本上,我想在函数中创建一个不同斜率的图形数组。当我使用append时,slope值(params[0])数组的长度是131,当它应该是24时,数组中的值都是错误的。如何使斜率数组,即每个斜率的值成为该函数运行时的值

    amin=0
    amax=0.024
    da=0.001
    a_list=np.arange(amin,amax,da)


    for a in a_list:
        mercury(a)    

        ##finding dtheat/dt 
        precession =[]
        #plot theta vs time

        Theta = [theta]

        Time = [time]
        #dtheta/dt dt=period



        #Fitting a straight line! 
        def linefit(x,m,b):
            return m*x+b
        params, param_cov = optimize.curve_fit(linefit,Time,Theta)
        plt.plot(a_list,params[0]*a_list+params[1],'--r',linewidth=2,label='fit')
        plt.plot(Time,Theta)
        plt.xlabel('Time')
        plt.ylabel('Theta')
        plt.title("time vs theta when alpha = {a}".format(a=a))
        plt.show()
        print('slope is %.3f' % (params[0]))  
        precession.append(params[0])

    plt.plot(a_list, precession)
    plt.show()


Tags: 函数timeplotdtplt数组paramslist
1条回答
网友
1楼 · 发布于 2024-10-01 13:26:29

你每次循环都要重置列表。我把它移到了圈外

已编辑:已创建新数组以包含用于分隔值的参数[0]

amin=0
amax=0.024
da=0.001
a_list=np.arange(amin,amax,da)

precession =[] # ADDED HERE
new_array = [] # ADDED HERE
for a in a_list:
    mercury(a)    

    ##finding dtheat/dt 

    #plot theta vs time

    Theta = [theta]

    Time = [time]
    #dtheta/dt dt=period
    for i in theta:
       precession.append(i/0.246)


    #Fitting a straight line! 
    def linefit(x,m,b):
        return m*x+b
    params, param_cov = optimize.curve_fit(linefit,Time,Theta)
    plt.plot(a_list,params[0]*a_list+params[1],' r',linewidth=2,label='fit')
    plt.plot(Time,Theta)
    plt.xlabel('Time')
    plt.ylabel('Theta')
    plt.title("time vs theta when alpha = {a}".format(a=a))
    plt.show()
    print('slope is %.3f' % (params[0]))  
    new_array.append(params[0]) # ADDED HERE

plt.plot(a_list, precession)
plt.show()

相关问题 更多 >