Python Beginner: Custom Printing in a Loop

I am a very new python user (had only a little prior experience with html / javascript as far as programming is concerned), and tried to find some ways to output only discontinuous numbers to my loop for basic modeling on bikes (10,000 lines of biker positions would be quite excessive : P).

I tried in this loop several “sensible” ways to report a condition where a floating point number is equal to its integer floor (int, floor division) in order to print out every 100 iterations or so:

 for i in range (0,10000):
  i = i + 1
  t = t + t_step #t is initialized at 0 while t_step is set at .01
  acceleration_rider1 = (power_rider1 / (70 * velocity_rider1)) - (force_drag1 / 70)
  velocity_rider1 = velocity_rider1 + (acceleration_rider1 * t_step)
  position_rider1 = position_rider1 + (velocity_rider1 * t_step)
  force_drag1 = area_rider1 * (velocity_rider1 ** 2) 
  acceleration_rider2 = (power_rider2 / (70 * velocity_rider1)) - (force_drag2 / 70)
  velocity_rider2 = velocity_rider2 + (acceleration_rider2 * t_step)
  position_rider2 = position_rider2 + (velocity_rider2 * t_step)
  force_drag2 = area_rider1 * (velocity_rider2 ** 2)

  if t == int(t): #TRIED t == t // 1 AND OTHER VARIANTS THAT DON'T WORK HERE:(
   print t, "biker 1", position_rider1, "m", "\t", "biker 2", position_rider2, "m" 
+3
source share
3 answers

for , i = i + 1.

t, % (modulo), .

# Log every 1000 lines.
LOG_EVERY_N = 1000

for i in range(1000):
  ... # calculations with i

  if (i % LOG_EVERY_N) == 0:
    print "logging: ..."
+11

100 ,

if i % 100 == 0: ...

, ,

if i and i % 100 == 0: ...

( , i = i + 1 , , i for - , , if ).

, t , t == int(t) , t_step 1.0 / 2**N N - , . ( decimal.Decimal, , float , ).

+3

, i. , . .

, , . , .01 t 100 , t == 1:

>>> sum([.01]*100)
1.0000000000000007

Therefore, when you compare the actual integer, you need to create a small margin. Something like this should work:

if abs(t - int(t)) < 1e-6:
 print t, "biker 1", position_rider1, "m", "\t", "biker 2", position_rider2, "m" 
+2
source

Source: https://habr.com/ru/post/1742694/


All Articles