Example 6: Multivariate Higher Order Derivatives
use f64ad_core::ComplexField; use f64ad_core::f64ad::{GlobalComputationGraphs}; fn main() { // Create a computation graph. let computation_graph = GlobalComputationGraphs::get(None, None); // Spawn an f64ad_ variables from computation graph. let v0 = computation_graph.spawn_variable(2.0); let v1 = computation_graph.spawn_variable(4.0); let result = v0.powf(v1); println!("Result: {:?}", result); println!("////////////////////////////////////////////////////////////////////////////////////"); // first derivative computations... let derivatives = result.backwards_mode_grad(true); let d_result_d_v0 = derivatives.wrt(&v0); let d_result_d_v1 = derivatives.wrt(&v1); println!("d_result_d_v0: {:?}", d_result_d_v0); println!("d_result_d_v0: {:?}", d_result_d_v1); println!("////////////////////////////////////////////////////////////////////////////////////"); // second derivative computations... let derivatives2_d_result_d_v0 = d_result_d_v0.backwards_mode_grad(true); let derivatives2_d_result_d_v1 = d_result_d_v1.backwards_mode_grad(true); let d2_result_dv0v0 = derivatives2_d_result_d_v0.wrt(&v0); let d2_result_dv0v1 = derivatives2_d_result_d_v0.wrt(&v1); let d2_result_dv1v0 = derivatives2_d_result_d_v1.wrt(&v0); let d2_result_dv1v1 = derivatives2_d_result_d_v1.wrt(&v1); println!("d2_result_dv0v0: {:?}", d2_result_dv0v0); println!("d2_result_dv0v1: {:?}", d2_result_dv0v1); println!("d2_result_dv1v0: {:?}", d2_result_dv1v0); println!("d2_result_dv1v1: {:?}", d2_result_dv1v1); println!("////////////////////////////////////////////////////////////////////////////////////"); // etc... }
Output
Result: f64ad_var_f(f64ad_var_f{ value: 16.0, node_idx: 2 })
////////////////////////////////////////////////////////////////////////////////////
d_result_d_v0: f64ad_var_f(f64ad_var_f{ value: 32.0, node_idx: 10 })
d_result_d_v0: f64ad_var_f(f64ad_var_f{ value: 11.090354888959125, node_idx: 12 })
////////////////////////////////////////////////////////////////////////////////////
d2_result_dv0v0: f64ad_var_f(f64ad_var_f{ value: 48.0, node_idx: 54 })
d2_result_dv0v1: f64ad_var_f(f64ad_var_f{ value: 30.18070977791825, node_idx: 56 })
d2_result_dv1v0: f64ad_var_f(f64ad_var_f{ value: 30.18070977791825, node_idx: 238 })
d2_result_dv1v1: f64ad_var_f(f64ad_var_f{ value: 7.687248222691222, node_idx: 240 })
////////////////////////////////////////////////////////////////////////////////////