autodiff.Dual¶
- class autodiff.Dual(val, der=1)¶
Primary data structure for forward mode automatic differentiation.
Dual numbers can be used as a data structure to store the value and derivative of a function. The value and derivative can be stored as the real and “dual” part of a dual number, respectively. The properties of a dual number lend itself nicely to a straightforward implementation of forward mode automatic differentiation.
- Parameters
- valfloat
The value of the Dual number.
- derndarray
The derivative of the Dual number.
See also
Examples
Construct a Dual number for a univariate function:
>>> x = ad.Dual(42) >>> x Dual(42, array([1]))
Construct a Dual number for a multivariate function with user-defined seed vector:
>>> x = ad.Dual(42, [1, 2]) >>> x Dual(42, array([1, 2]))
Construct multiple Dual numbers from array of scalars:
>>> x, y, z = ad.Dual.from_array([1, 2, 4]) >>> x Dual(1, array([1, 0, 0])) >>> y Dual(2, array([0, 1, 0]))
Create a function from multiple Dual numbers:
>>> x, y, z = ad.Dual.from_array([1, 2, 4]) >>> f = (x * y)/z >>> f.val 0.5 >>> f.der array([0.5, 0.25, -0.125])
- Attributes
ndim
Return the number of dimensions of the Dual number.
Methods
constant
(val[, ndim])Create a Dual number representing a constant.
from_array
(X)Generate Dual numbers for a multivariable function.
- property ndim¶
Return the number of dimensions of the Dual number.
- Parameters
- selfDual
- Returns
- outint
Number of dimensions.
Examples
>>> ad.Dual(-5, [6.2]).ndim 1
More than one dimension:
>>> ad.Dual(42, [1, 2]).ndim 2
- static constant(val, ndim=1)¶
Create a Dual number representing a constant.
- Parameters
- valint or float
Value of dual number.
- ndimint, optional
ndim
is the number of dimensions of the zero derivative vector.
- Returns
- outDual
Dual number of value
val
with zero derivative vector.
Notes
Derivative vector of length
ndim
will be filled with zeros.Examples
>>> ad.Dual.constant(42) Dual(42, array([0.]))
Constant with more than one dimension:
>>> ad.Dual.constant(7, 2) Dual(7, array([0., 0.]))
- static from_array(X)¶
Generate Dual numbers for a multivariable function.
- Parameters
- Xarray
Array of numbers which will be values of Dual numbers.
- Returns
- outDual number generator
Dual numbers of value
X[i]
with zero derivative vector where the i-th element has a value of 1.
Examples
>>> x, y = ad.Dual.from_array([1, 42]) >>> x Dual(1, array([1., 0.])) >>> y Dual(42, array([0., 1.]))