Skip to content

Instantly share code, notes, and snippets.

@erutuf
Created June 6, 2016 18:10
Show Gist options
  • Save erutuf/55d00b658ef57477c3c9d1cf20464ca3 to your computer and use it in GitHub Desktop.
Save erutuf/55d00b658ef57477c3c9d1cf20464ca3 to your computer and use it in GitHub Desktop.
(* sample code of automatic differentiation in Coq *)
Require Import QArith.
Open Scope Q_scope.
Definition QFunc := Q -> Q.
Parameter der_rel : QFunc -> QFunc -> Prop.
Axiom add_der : forall f g f' g', der_rel f f' -> der_rel g g' ->
der_rel (fun x => f x + g x) (fun x => f' x + g' x).
Axiom scalar_der : forall c f f', der_rel f f' -> der_rel (fun x => c * f x) (fun x => c * f' x).
Axiom leibnitz_der : forall f g f' g', der_rel f f' -> der_rel g g' ->
der_rel (fun x => f x * g x) (fun x => f' x * g x + f x * g' x).
Axiom const_der : forall (c : Q), der_rel (fun _ => c) (fun _ => 0).
Axiom id_der : der_rel (fun x => x) (fun _ => 1).
Ltac calc_der := eexists;
repeat (apply add_der || apply scalar_der || apply leibnitz_der || apply const_der || apply id_der).
(* differentiate x^2 *)
Example derivative_x_sq : { f | der_rel (fun x => x * x) f }.
calc_der.
Defined.
Eval simpl in proj1_sig derivative_x_sq.
(*
= fun x : Q => 1 * x + x * 1
: QFunc
*)
(* differenciate cx + b *)
Example derivative_linear (b c : Q) : { f | der_rel (fun x => c * x + b) f }.
calc_der.
Defined.
Eval simpl in proj1_sig (derivative_linear (inject_Z 3) (inject_Z 2)).
(*
= fun _ : Q => inject_Z 2 * 1 + 0
: QFunc
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment