Dual2#

class rateslib.dual.Dual2(real, vars, dual, dual2)#

Dual number data type to perform first derivative automatic differentiation.

Parameters:
  • real (float, int) – The real coefficient of the dual number

  • vars (tuple of str) – The labels of the variables for which to record derivatives. If empty, the dual number represents a constant, equivalent to a float.

  • dual (list of float) – First derivative information contained as coefficient of linear manifold. Defaults to an array of ones the length of vars if empty.

  • dual2 (list of float) – Second derivative information contained as coefficients of quadratic manifold. Defaults to a 2d array of zeros the size of vars if empty. These values represent a 2d array but must be given as a 1d list of values in row-major order.

Attributes

Variables:
  • real – float

  • vars – sequence of str

  • dual – 1d ndarray

  • dual2 – 2d ndarray

See also

Dual: Dual number data type to perform first derivative automatic differentiation.

Examples

In [1]: from rateslib.dual import Dual2, gradient

In [2]: def func(x, y):
   ...:     return 5 * x**2 + 10 * y**3
   ...: 

In [3]: x = Dual2(1.0, ["x"], [], [])

In [4]: y = Dual2(1.0, ["y"], [], [])

In [5]: gradient(func(x,y), ["x", "y"], order=2)
Out[5]: 
array([[10.,  0.],
       [ 0., 60.]])

Methods Summary

vars_from(other, real, vars, dual, dual2)#

Create a Dual2 object with vars linked with another.

Parameters:
  • other (Dual) – The other Dual from which to link vars.

  • real (float, int) – The real coefficient of the dual number

  • vars (tuple of str) – The labels of the variables for which to record derivatives. If empty, the dual number represents a constant, equivalent to a float.

  • dual (list of float) – First derivative information contained as coefficient of linear manifold. Defaults to an array of ones the length of vars if empty.

  • dual2 (list of float) – Second derivative information contained as coefficients of quadratic manifold. Defaults to a 2d array of zeros the size of vars if empty. These values represent a 2d array but must be given as a 1d list of values in row-major order.

Return type:

Dual2

Notes

Variables are constantly checked when operations are performed between dual numbers. In Rust the variables are stored within an ARC pointer. It is much faster to check the equivalence of two ARC pointers than if the elements within a variables Set, say, are the same and in the same order. This method exists to create dual data types with shared ARC pointers directly.

In [1]: from rateslib import Dual2

In [2]: x1 = Dual2(1.0, ["x"], [], [])

In [3]: x2 = Dual2(2.0, ["x"], [], [])

# x1 and x2 have the same variables (["x"]) but it is a different object
In [4]: x1.ptr_eq(x2)
Out[4]: False

In [5]: x3 = Dual2.vars_from(x1, 3.0, ["x"], [], [])

# x3 contains shared object variables with x1
In [6]: x1.ptr_eq(x3)
Out[6]: True