Home > database >  How to loop forward and backward in a range in python?
How to loop forward and backward in a range in python?

Time:11-18

enter image description here

I want to program motion as described in the drawing above. The angle changes according to this equation:theta = Amp*np.sin(2*np.pi*ftheta*p) . I am looping through p(time) and that is the only variable in this equation, nothing else changes. How do i make it stop once it reaches the amplitude and make it start going in the reverse direction until it hits the -(amplitude)

import numpy as np
import matplotlib.pyplot as plt
import math

r=20
h=1.7
num_of_steps=100
emp=3
phi = []
theta = []
time=np.arange(0,100,1)
fphi = 1
ftheta = 1
Amp = 90
for j in time:
kampas = np.degrees(2*np.pi*fphi*j)
kitaskampas = np.degrees(np.sin(2*np.pi*ftheta*j))
if kampas > 360:
    temp = math.floor(kampas/360)
    sukasi = round(kampas - 360*temp)
    print(sukasi)
    phi.append(sukasi)
if kitaskampas == Amp:

print(phi)

CodePudding user response:

have you tried to write some code yourself? If it is so, please share so we can help.

As far as I understood while loop can work for you:

exit_flag = 0
time = 0
theta = 0
amplitude = 1
while(exit_flag == 0):
    if(amplitude > 0):
        time = time   1
    else:
        time = time - 1
    
    theta = some_equasion_dependning_of_time(time)
    
    if(we_wanna_exit)
        exit_flag = 1

CodePudding user response:

I couldn't understand what really is going with kampas variable. However, this is a minimal example to move between two limit. You can place your calculations where we change value variable.

direction = 1
_range = 90
unit_of_change = 7
value = 0
def looper():
   global direction, value
   
   if(value < -_range):
      #if value(theta) hits -amplitude change its direction
      direction = 1
   if(value > _range):
      #if value(theta) hits  amplitude change its direction reverse
      direction = 0

   #make required calculations with your theta
   if direction:
      value  = unit_of_change
   else:
      value -= unit_of_change


unit_of_process = 200

#run for a while
while unit_of_process:
   print(value, end="  ")
   looper()
   unit_of_process -= 1
  • Related