brainpy.math.controls.while_loop(body_fun, cond_fun, dyn_vars, operands)[source]#

while-loop control flow with Variable.

Note the diference between for_loop and while_loop:

  1. while_loop does not support accumulating history values.

  2. The returns on the body function of for_loop represent the values to stack at one moment. However, the functional returns of body function in while_loop represent the operands’ values at the next moment, meaning that the body function of while_loop defines the updating rule of how the operands are updated.

>>> import brainpy.math as bm
>>> a = bm.Variable(bm.zeros(1))
>>> b = bm.Variable(bm.ones(1))
>>> def cond(x, y):
>>>    return x < 6.
>>> def body(x, y):
>>>    a.value += x
>>>    b.value *= y
>>>    return x + b[0], y + 1.
>>> res = bm.while_loop(body, cond, dyn_vars=[a, b], operands=(1., 1.))
>>> res
(10.0, 4.0)

New in version 2.1.11.

  • body_fun (callable) – A function which define the updating logic. It receives one argument for operands, without returns.

  • cond_fun (callable) – A function which define the stop condition. It receives one argument for operands, with one boolean value return.

  • dyn_vars (Variable, sequence of Variable, dict) – The dynamically changed variables.

  • operands (Any) – The operands for body_fun and cond_fun functions.