Dual numbers and uncertainties
pydual
provides an implementation of autodifferentiation with dual numbers
that allows to effortlessly model and propagate uncertainties through calculations.
Example
import numpy as np
from pydual.core import dual
# load/create data as a numpy array like you already do
x_best = np.array([3.14, 4.20, 5.25, 6.32, 8.11])
x_errs = np.array([0.01, 0.02, 0.01, 0.01, 0.02]) #(1)!
# store the data as a dual number
x = dual.from_data(x_best, sigma=x_errs) #(2)!
# access the real and dual parts
print(x.dreal) # the real part of `x`: original `x_best` data (3)
print(x.ddual) # the dual part of `x`: embeds `x_errs` data (4)
# evaluate uncertainties
print(x.ddual.std()) # evaluate the standard deviation of all random variables (5)
print(x.display()) # print `x` as an array of '<best> ± <delta>' elements (6)
# calculate array sum
print(x.sum().display()) #(7)!
# calculate unweighted array average (arithmetic mean)
print(x.average(weights=False).display())
- Error bars on
x_best
- The
x
variable is adual
instance and represents a vector (1D array) of dual numbers: you can think of it as an array of random variables, all normally distributed (with standard deviations dictated byx_errs
) and stochastically independent. - This attribute is called
.dreal
to avoid confusion with the.real
attribute ofcomplex
numbers (we currently don't support complex numbers in the real or dual parts, but we'd like to in the future) - the leadingd
stands for “dual number”. - This attribute is called
.ddual
(and not.dual
) for symmetry with.dreal
. - If the random variables are normally distributed, their standard deviations are the best estimators for uncertainties. Note that the result is equal to
x_errs
. - The
.display()
method uses.ddual.std()
under the hood, hence uncertainties are estimated this way. - Note that the uncertainty is automatically calculated as the square root of the sum of the squares of the elements of
x.ddual.std()
, because they are independent.
Future directions
pydual
aims to implement the following features:
- Complex numbers support
- Custom/arbitrary error distribution (currently it implicitely only supports normal distributions)
- Full Array API support