有没有办法在 Python 中定义一个浮点数组?

Is there a way to define a float array in Python?

为了我的天文学作业,我需要模拟行星围绕太阳的椭圆轨道。为此,我需要使用 for 循环来重复计算行星的运动。但是,每次我尝试 运行 程序时,我都会收到以下错误:

RuntimeWarning: invalid value encountered in power
r=(x**2+y**2)**1.5
Traceback (most recent call last):
File "planetenstelsel3-4.py", line 25, in <module>
ax[i] = a(x[i],y[i])*x[i]
ValueError: cannot convert float NaN to integer

我做了一些测试,我认为问题在于计算出的值大于适合整数的值,并且数组被定义为int数组。因此,如果有一种方法可以将它们定义为浮点数组,也许它会起作用。这是我的代码:

import numpy as np
import matplotlib.pyplot as plt

dt = 3600 #s
N = 5000
x = np.tile(0, N)
y = np.tile(0, N)
x[0] = 1.496e11 #m
y[0] = 0.0
vx = np.tile(0, N)
vy = np.tile(0, N)
vx[0] = 0.0
vy[0] = 28000 #m/s
ax = np.tile(0, N)
ay = np.tile(0, N)
m1 = 1.988e30 #kg
G = 6.67e-11 #Nm^2kg^-2

def a(x,y):
    r=(x**2+y**2)**1.5
    return (-G*m1)/r

for i in range (0,N):
    r = x[i],y[i]
    ax[i] = a(x[i],y[i])*x[i]
    ay[i] = a(x[i],y[i])*y[i]
    vx[i+1] = vx[i] + ax[i]*dt
    vy[i+1] = vy[i] + ay[i]*dt
    x[i+1] = x[i] + vx[i]*dt 
    y[i+1] = y[i] + vy[i]*dt    
plt.plot(x,y)
plt.show()

前几行只是一些起始参数。

提前感谢您的帮助!

当你进行物理模拟时,你绝对应该为一切使用浮点数。 0 是 Python 中的整数常量,因此 np.tile 创建整数数组;使用 0.0 作为 np.tile 的参数来做浮点数组;或者最好使用 np.zeros(N) 代替:

您可以从其 dtype 成员检查任何数组变量的数据类型:

>>> np.tile(0, 10).dtype
dtype('int64')
>>> np.tile(0.0, 10).dtype
dtype('float64')
>>> np.zeros(10)
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
>>> np.zeros(10).dtype
dtype('float64')

要获得 float32 的归零数组,您需要提供 float32 作为参数:

>>> np.tile(np.float32(0), 10)
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)

或者,最好将 zeros 与已定义的 dtype:

一起使用
>>> np.zeros(10, dtype='float32')
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)

您需要 x = np.zeros(N),等等:这会将数组声明为浮点数组。

这是在数组中放置零的标准方法(np.tile() 便于使用固定数组创建平铺)。