Я не знаю, почему Python выдает эту ошибку - PullRequest
0 голосов
/ 12 октября 2019

Я пытаюсь создать программу, которая отображает скорость шара при свободном падении по сравнению со скоростью шара при воздействии силы сопротивления, так что F_drag = -Cv ^ 2, где C - постоянная (m * g) /100. Мои входные данные: 5 для m, 5 для tf и 0.1 для dt.

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

m = float(input("Input the mass of the ball in kilograms: "))
tf = float(input("Input a specified time of fall in seconds: "))
dt = float(input("Input the time step for each calculation in seconds: "))

imaxFloat = tf/dt   # The total number of time steps as a floating point number with remainder
imax = int(round(imaxFloat))   # Converts the float to the nearest integer 

v0 = 0       # Velocity at t = 0
g = 9.8       # Accleration due to gravity
i = 0       # Initial counter value
i2 = 0     # Initial counter value 2
c = (m*g)/100     # Constant in drag equation

t1 = np.array([0])
v1 = np.array([v0])
t2 = np.array([0])
v2 = np.array([v0])

drag_a = ((m*g)-(c*v1*v1))/m     # Acceleration of ball with drag

while i < imax:
    t1 = np.append(t1, t1[i] + dt)
    v1 = np.append(v1, v1[i] - g * dt )
    i = i + 1

while i2 < imax:
    t2 = np.append(t2, t2[i] + dt)
    v2 = np.append(v2, v2[i] - drag_a * dt)
    i2 = i2 + 1

plt.plot(t1, v1, label = "Neglecting air resistance")
plt.plot(t2, v2, label = "With air resistance")

Python выдает эту ошибку:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-6-10c7e3224e87> in <module>
     30 
     31 while i2 < imax:
---> 32     t2 = np.append(t2, t2[i] + dt)
     33     v2 = np.append(v2, v2[i] - drag_a * dt)
     34     i2 = i2 + 1

IndexError: index 50 is out of bounds for axis 0 with size 1

Мне нужна помощь в целом по этой проблеме, но такженайти решение этой ошибки. Спасибо!

Ответы [ 2 ]

0 голосов
/ 12 октября 2019

Ваши циклы while действительно не должны использовать np.append. Это медленно.

In [119]: t1 = np.array([0]) 
     ...: i=0 
     ...: while i < 10: 
     ...:     t1 = np.append(t1, t1[i] + .1) 
     ...:     i += 1 
     ...:                                                                       
In [120]: t1                                                                    
Out[120]: array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])

Добавление в список происходит быстрее:

In [121]: t1 = [0] 
     ...: i=0 
     ...: for i in range(10): 
     ...:     t1.append(t1[-1] + .1)     # t1[-1] the last, latest, value
     ...:      
     ...:                                                                       
In [122]: t1                                                                    
Out[122]: 
[0,
 0.1,
 0.2,
 0.30000000000000004,
 0.4,
 0.5,
 0.6,
 0.7,
 0.7999999999999999,
 0.8999999999999999,
 0.9999999999999999]
In [123]: np.array(_)                                                           
Out[123]: array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])

Еще лучше использовать arange:

In [124]: np.arange(11)*0.1                                                     
Out[124]: array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])

In [127]: np.linspace(0,1,11)                                                   
Out[127]: array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
0 голосов
/ 12 октября 2019

Во втором цикле while вы должны использовать i2 в качестве индексной переменной. Поскольку во время первой итерации цикла, t2[i] на самом деле t2[50], но в то время, t2 имеет только один элемент, поэтому индекс выходит за пределы.

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

m = float(input("Input the mass of the ball in kilograms: "))
tf = float(input("Input a specified time of fall in seconds: "))
dt = float(input("Input the time step for each calculation in seconds: "))

imaxFloat = tf/dt   # The total number of time steps as a floating point number with remainder
imax = int(round(imaxFloat))   # Converts the float to the nearest integer 

v0 = 0       # Velocity at t = 0
g = 9.8       # Accleration due to gravity
i = 0       # Initial counter value
i2 = 0     # Initial counter value 2
c = (m*g)/100     # Constant in drag equation

t1 = np.array([0])
v1 = np.array([v0])
t2 = np.array([0])
v2 = np.array([v0])

drag_a = ((m*g)-(c*v1*v1))/m     # Acceleration of ball with drag

while i < imax:
    t1 = np.append(t1, t1[i] + dt)
    v1 = np.append(v1, v1[i] - g * dt )
    i = i + 1

while i2 < imax:
    t2 = np.append(t2, t2[i2] + dt)
    v2 = np.append(v2, v2[i2] - drag_a * dt)
    i2 = i2 + 1

plt.plot(t1, v1, label = "Neglecting air resistance")
plt.plot(t2, v2, label = "With air resistance")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...