Home > OS >  For loop to calculate a mathematical expression
For loop to calculate a mathematical expression

Time:10-17

 image description goes hereHow to write a Python for loop that calculate the following xN1i0 and xN2i0 for N times ?

xSpanN1=0.232e-6 
xSpanN2=0.09688e-6

xN1i0 = 0.0
xN2i0 = ((xSpanN1/2) (xSpanN2/2)) xN1i0

xN1i1 = ((xSpanN1/2) (xSpanN2/2)) xN2i0
xN2i1 = ((xSpanN1/2) (xSpanN2/2)) xN1i1

xN1i2 = ((xSpanN1/2) (xSpanN2/2)) xN2i1
xN2i2 = ((xSpanN1/2) (xSpanN2/2)) xN1i2

xN1i3 = ((xSpanN1/2) (xSpanN2/2)) xN2i2
xN2i3 = ((xSpanN1/2) (xSpanN2/2)) xN1i3
....
..
.
.

CodePudding user response:

drop the numbers at the end of the names for iterations, just use two variables and put them in a for loop.

xSpanN1=0.232e-6 
xSpanN2=0.09688e-6

xN1i = 0.0
xN2i = ((xSpanN1/2) (xSpanN2/2)) xN1i

for _ in range(20):
    xN1i = ((xSpanN1/2) (xSpanN2/2)) xN2i
    xN2i = ((xSpanN1/2) (xSpanN2/2)) xN1i

CodePudding user response:

You don't really need two variables, calculate xN1i and remove ((xSpanN1 / 2) (xSpanN2 / 2)) from it to get xN12

xSpanN1 = 0.232e-6
xSpanN2 = 0.09688e-6
xSpan = ((xSpanN1 / 2)   (xSpanN2 / 2))

xN1i = 0.0
for _ in range(10):
    xN1i  = xSpan
xN12 = xN1i - xSpan

Or with generator expresion and sum

xN1i = sum(xSpan for _ in range(10))
xN12 = xN1i - xSpan

CodePudding user response:

increment = xSpanN1/2 xSpanN2/2
[xN1i0,xN1i0,
    xN1i1,xN1i1,
    xN1i2,xN1i2,
    xN1i3,xN1i3,
    #....
] = range(increment*N, increment)

You could dynamically generate the name xN1i0 etc. with, for instance, eval.

eval('[' ,','.join(['xN1i{},xN2i{}'.format(n,n) 
                for n in range(N)]) ']') =
    range(increment*N, increment)
  • Related