使用 np.savetxt 将数据保存在多列中

计算科学 Python 计算物理学 麻木的
2021-12-29 10:11:17

我设法为以下问题编写了以下代码:

弹丸的水平和垂直位移由下式给出:

x=v0tcos(θ)

y=v0tsin(θ)12gt2

  • 考虑时间间隔为t[0,60]seconds. 编写 Python 代码来绘制水平和最大垂直位移(意思是ymax.作为一个函数x) 与初始速度40m/sec对于同一图表上的四个角度(30、45、60 和 75 度)。然后将数据保存在文本文件中。

我的代码是:

import numpy as np
import matplotlib.pyplot as plt

v = 40
g = 9.8

def x(theta):
    return ((v*t)*np.cos(theta*np.pi/180))

def y(theta):
    return ((v*t)*np.sin(theta*np.pi/180))-((0.5*g)*(t**2))


for theta in range(30, 90, 15):
    tmax = v * np.sin(theta*np.pi/180)/g  #Time to reach maximum height
    t = np.linspace(0, tmax,600)
    
    X = x(theta)  #Maximum horizontal displacement at tmax
    Y = y(theta)  #Maximum vertical displacement at tmax
    
    plt.plot(X, Y, label=theta)
    
    table=np.column_stack((t,X, Y))                             
np.savetxt("projectile.txt", table, fmt='%.3e', delimiter="  ")  # just saves 3 columns :(


    
plt.xlabel("x")
plt.ylabel("y")
plt.title("Maximum Height as a Function of Angle")
plt.legend()
plt.show()

在此处输入图像描述

我成功地得到了情节;但是,保存的数据仅包含 3 列,而应该是 9 列。

请问如何保存所有数据?非常感谢您的帮助。

1个回答

好吧,您在每个循环中“覆盖”表......因此,当 for 循环终止时,表只有 t、X、Y 列,用于 theta=75。

尝试这个:

columns = []

for theta in range(30, 90, 15):
    tmax = v * np.sin(theta*np.pi/180)/g  #Time to reach maximum height
    t = np.linspace(0, tmax,600)
    
    X = x(theta)  #Maximum horizontal displacement at tmax
    Y = y(theta)  #Maximum vertical displacement at tmax
    
    plt.plot(X, Y, label=theta)
    
    columns += [t,X,Y]
                          
np.savetxt("projectile.txt", np.column_stack(columns), fmt='%.3e', delimiter="  ")