Home > Software design >  How can I print the value at each t=1000 in a way better than the following?
How can I print the value at each t=1000 in a way better than the following?

Time:06-07

Consider:

dt=10**(-3)
for i in range(1,10**7 1):
    t=i*dt;
    kounter=e**(t*(dt**3))
    if t==1000 or t==2000 or t==3000 or t==4000 or t==5000 or t==6000:
        print(kounter)   

Now the above code in itself might be written in an infinitely better way but that is just to show what I want to do in my actual code in which I want to print the value of a variable at each 1000 step till the end (note in above I did it only till 6000 but I want it till 10,000) which looks absurd if the end time is very large.

I am sure there is a prettier and more efficient way of doing it.

CodePudding user response:

you probably looking for this %

# when the remainder of t divided by 1000 equals zero
if t % 1000 == 0:
    print(kounter)

CodePudding user response:

You can use the rest of the division of your loop variable by the number of steps you want to run between samples for printing the value of the variable.

STEPS_PER_SAMPLE = 1000 # You can change this as you see fit
dt=10**(-3)
for i in range(1,100001):
    t=i*dt;
    kounter=e**(t*(dt**3))
    if i % STEPS_PER_SAMPLE == 0:
        print(kounter)  

CodePudding user response:

You can use the equivalence between integer division and true division

if (t//1000)==(t/1000):
    print(konter)

CodePudding user response:

Define a look-up "list" which contains multiple of 1000.

start, end, step = 1000, 11000, 10**3 # outside the for-loop
...
    if i in range(start, end, step)):
        ...

CodePudding user response:

This is the efficient way:

dt=10**(-3)
for i in range(1,100001):
    t=i*dt;
    kounter=e**(t*(dt**3))
    if t % 1000 == 0:
        print(kounter)  
  • Related