while_loop

Contents

while_loop#

class brainpy.math.while_loop(body_fun, cond_fun, operands, dyn_vars=None, child_objs=None)[source]#

while-loop control flow with Variable.

Changed in version 2.3.0: dyn_vars has been changed into a default argument. Please change your call from while_loop(f1, f2, dyn_vars, operands) to while_loop(f1, f2, operands, dyn_vars).

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, operands=(1., 1.))
>>> res
(10.0, 4.0)

New in version 2.1.11.

Parameters:
  • 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.

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

  • dyn_vars (Variable, sequence of Variable, dict) –

    The dynamically changed variables.

    Deprecated since version 2.4.0: No longer need to provide dyn_vars. This function is capable of automatically collecting the dynamical variables used in the target func.

  • child_objs (optional, dict, sequence of BrainPyObject, BrainPyObject) –

    The children objects used in the target function.

    Deprecated since version 2.4.0: No longer need to provide child_objs. This function is capable of automatically collecting the children objects used in the target func.