Python - break loop for (Python)

 
Vista:
sin imagen de perfil

break loop for (Python)

Publicado por chris (2 intervenciones) el 18/03/2015 10:21:51
Hola,

que tal?
Soy nuevo en el mundo de la programación y necesito una ayuda con el siguiente problema por favor :)
En el siguiente código, donde se utiliza el método numérico de Euler para representar la trayectoria de una avión de papel, me gustaría que el loop for (# time loop - Euler method) de la ultima linea parase cuando la la posición vertical (y) sea igual a 0 ( o sea prescindir de los valores negativos de la posición vertical).

muchas gracias!!!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# model parameters:
g = 9.8      # gravity in m s^{-2}
v_t = 4.9   # trim velocity in m s^{-1}   
C_D = 1/50.  # drag coefficient --- or D/L if C_L=1
C_L = 1.0    # for convenience, use C_L = 1
 
### set initial conditions ###
v0 = v_t     # start at the trim velocity (or add a delta)
theta0 = pi/4  # initial angle of trajectory
x0 = 0.0     # horizotal position is arbitrary
y0 = 0.0     # initial altitude
 
def f(u):
 
    v = u[0]
    theta = u[1]
    x = u[2]
    y = u[3]
    return numpy.array([-g*sin(theta) - C_D/C_L*g/v_t**2*v**2,
                      -g*cos(theta)/v + g/v_t**2*v,
                      v*cos(theta),
                      v*sin(theta)])
 
def euler_step(u, f, dt):
 
    return u + dt * f(u)
 
T = 100.0                          # final time
dt = 0.001                           # time increment
N = int(T/dt) + 1                  # number of time-steps
t = numpy.linspace(0.0, T, N)      # time discretization
 
# initialize the array containing the solution for each time-step
u = numpy.empty((N, 4))
u[0] = numpy.array([v0, theta0, x0, y0])# fill 1st element with initial values
 
# time loop - Euler method
 
for n in range(N-1):
 
    u[n+1] = euler_step(u[n], f, dt)
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de xve
Val: 2.239
Plata
Ha mantenido su posición en Python (en relación al último mes)
Gráfica de Python

break loop for (Python)

Publicado por xve (1646 intervenciones) el 18/03/2015 20:35:34
Hola Chris, he intentado probar tu código y me da varios errores...

Sobre lo que comentas, no se ver en el bucle al que haces referencia la variable y...

Si nos puedes comentar con mas detalle...
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

break loop for (Python)

Publicado por chris (2 intervenciones) el 18/03/2015 23:46:17
Hola, te copié todo el código y a mi funciona sin darme errores.

En el codigo se utiliza el metodo de Euler que discretiza una serie de ecuaciones diferenciales mediante un paso de tiempo dt = 0.1. El metodo de Euler es el siguiente:

u[n+1] = u[n] + dt *f(u) [n]

El vector u corresponde a la soluciones y tiene dimensión N = 4 , donde N=1 corresponde a la velocidad, N =2 al angulo de la trayectoria, N = 3 la posición horizontal y N = 4 la posición vertical.

En f(u) hay las ecuaciones que multiplicadas por el paso de tiempo devuelven las soluciones.

Muchas gracias

saludos

christian

from math import sin, cos, log, ceil
import numpy
from matplotlib import pyplot
%matplotlib inline
from matplotlib import rcParams
rcParams['font.family'] = 'serif'
rcParams['font.size'] = 16
# model parameters:
g = 9.8 # gravity in m s^{-2}
v_t = 30.0 # trim velocity in m s^{-1}
C_D = 1/40. # drag coefficient --- or D/L if C_L=1
C_L = 1.0 # for convenience, use C_L = 1

### set initial conditions ###
v0 = v_t # start at the trim velocity (or add a delta)
theta0 = 0.0 # initial angle of trajectory
x0 = 0.0 # horizotal position is arbitrary
y0 = 1000.0 # initial altitude

def f(u):
"""Returns the right-hand side of the phugoid system of equations.

Parameters
----------
u : array of float
array containing the solution at time n.

Returns
-------
dudt : array of float
array containing the RHS given u.
"""

v = u[0]
theta = u[1]
x = u[2]
y = u[3]
return numpy.array([-g*sin(theta) - C_D/C_L*g/v_t**2*v**2,
-g*cos(theta)/v + g/v_t**2*v,
v*cos(theta),
v*sin(theta)])def euler_step(u, f, dt):
"""Returns the solution at the next time-step using Euler's method.

Parameters
----------
u : array of float
solution at the previous time-step.
f : function
function to compute the right hand-side of the system of equation.
dt : float
time-increment.

Returns
-------
u_n_plus_1 : array of float
approximate solution at the next time step.
"""

return u + dt * f(u)

T = 100.0 # final time
dt = 0.1 # time increment
N = int(T/dt) + 1 # number of time-steps
t = numpy.linspace(0.0, T, N) # time discretization

# initialize the array containing the solution for each time-step
u = numpy.empty((N, 4))
u[0] = numpy.array([v0, theta0, x0, y0])# fill 1st element with initial values

# time loop - Euler method
for n in range(N-1):

u[n+1] = euler_step(u[n], f, dt)

# get the glider's position with respect to the time
x = u[:,2]
y = u[:,3]

# visualization of the path
pyplot.figure(figsize=(8,6))
pyplot.grid(True)
pyplot.xlabel(r'x', fontsize=18)
pyplot.ylabel(r'y', fontsize=18)
pyplot.title('Glider trajectory, flight time = %.2f' % T, fontsize=18)
pyplot.plot(x,y, 'k-', lw=2);
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar