Dual number for automatic differentation
Construct a dual number with the specified real and dual parts. In the case where a single argument is passed that is not a dual number, the imaginary part of the result will be zero.
Converts the dual number to a string representation. The second form of this function is usually not called directly; instead, it is used via std.string.format, as shown in the examples below. Supported format characters are 'e', 'f', 'g', 'a', and 's'. See the std.format and std.string.format documentation for more information.
To calculate the derivate of a function, set the dual part of the variable by which you want to derive to 1. Other dual numbers should have dual part of 0. Then just calculate the function like you would with normal numbers. The real part is always identically to the result with normal numbers. After the calculation the dual part holds the derivate of the function.
1 import std.math; 2 // f(x) = x⁵ f'(x) = 5x⁴ for x = 2 3 const x = Dual!double(2.0, 1.0); 4 auto f2 = x^^5; 5 assert(approxEqual(f2.re, 2.0^^5)); 6 assert(approxEqual(f2.du, 5.0 * 2.0^^4)); 7 8 // f(x) = 3x² f'(x) = 6x for x = 2 9 f2 = 3.0 * x * x; 10 assert(approxEqual(f2.re, 3.0 * 2.0 * 2.0)); 11 assert(approxEqual(f2.du, 6.0 * 2.0)); 12 13 // f(x) = 3/(1-x) f'(x) = 3/(1-x)^2 for x = 2 14 f2 = 3.0/(1.0 - x); 15 assert(approxEqual(f2.re, -3.0)); 16 assert(approxEqual(f2.du, 3.0)); 17 18 // f(x) = 3exp(2x), f'(x) = 6exp(2x) for x = 2 19 f2 = 3 * exp(2 * x); 20 assert(approxEqual(f2.re, 3 * std.math.exp(4.0))); 21 assert(approxEqual(f2.du, 6 * std.math.exp(4.0)));