Difference between revisions of "Calculate a derivative"

From CodeCodex

(Common Lisp)
(Common Lisp)
Line 97: Line 97:
 
                         (* ,(caddr e) ,(d (cadr e) x))))))
 
                         (* ,(caddr e) ,(d (cadr e) x))))))
  
(defun string_of (e)
+
(defvar *e* '(+ (+ (* a (* x x)) (* b x)) c))
  (cond
+
  ((atom e) e (format nil "~A" e))
+
  (t (concatenate 'string
+
  "(" (string_of (cadr e))
+
  (format nil "~A" (car e))
+
  (string_of (caddr e)) ")"))))
+
  
(defvar e '(+ (+ (* a (* x x)) (* b x)) c))
+
(d *e* 'x)
 
+
(string_of (d e 'x))
+
 
</pre>
 
</pre>
  
 
The result is printed as:
 
The result is printed as:
  
<pre>((((A*((X*1)+(X*1)))+((X*X)*0))+((B*1)+(X*0)))+0)</pre>
+
<pre>(+ (+ (+ (* A (+ (* X 1) (* X 1))) (* (* X X) 0)) (+ (* B 1) (* X 0))) 0)</pre>
  
 
==F#==
 
==F#==

Revision as of 16:23, 10 January 2007

Related content:

Compute and print the derivative of the symbolic expression a x^2 + b x + c.

C++

#include <iostream>

using namespace std;

class Var;

class Base {
public:
  virtual ~Base() {};
  virtual const Base *clone() = 0;
  virtual const Base *d(const string &v) const = 0;
  virtual ostream &print(ostream &o) const = 0;
};

ostream &operator<<(ostream &o, const Base &e) { e.print(o); return o; }

class Int : public Base {
  const int n;
public:
  Int(int m) : n(m) {}
  ~Int() {}
  const Base *clone() { return new Int(n); }
  const Base *d(const string &v) const { return new Int(0); }
  ostream &print(ostream &o) const { return o << n; }
};

class Var : public Base {
  const string var;
public:
  Var(string v) : var(v) {}
  ~Var() {}
  const Base *clone() { return new Var(var); }
  const Base *d(const string &v) const { return new Int(var == v ? 1 : 0); }
  ostream &print(ostream &o) const { return o << var; }
};

class Plus : public Base {
  const Base *e1, *e2;
public:
  Plus(const Base *a, const Base *b) : e1(a), e2(b) {}
  ~Plus() { delete e1; delete e2; }
  const Base *clone() { return new Plus(e1, e2); }
  const Base *d(const string &v) const { return new Plus(e1->d(v), e2->d(v)); }
  ostream &print(ostream &o) const
  { return o << "(" << *e1 << " + " << *e2 << ")"; }
};

class Times : public Base {
  const Base *e1, *e2;
public:
  Times(const Base *a, const Base *b) : e1(a), e2(b) {}
  ~Times() { delete e1; delete e2; }
  const Base *clone() { return new Times(e1, e2); }
  const Base *d(const string &v) const
  { return new Plus(new Times(e1, e2->d(v)), new Times(e1->d(v), e2)); }
  ostream &print(ostream &o) const { return o << "(" << *e1 << " * " << *e2 << ")"; }
};

class Expr {
public:
  Base *e;
  Expr(Base *a) : e(a) {}
};

const Expr operator+(const Expr e1, const Expr e2)
{ return Expr(new Plus(e1.e->clone(), e2.e->clone())); }
const Expr operator*(const Expr e1, const Expr e2)
{ return Expr(new Times(e1.e->clone(), e2.e->clone())); }

ostream &operator<<(ostream &o, const Expr e) { return o << e.e; }

int main() {
  Var vx("x"), va("a"), vb("b"), vc("c");
  Expr x(&vx), a(&va), b(&vb), c(&vc);
  Expr e = a*x*x + b*x + c;
  cout << "d(" << *(e.e) << ", x) = " << *(e.e->d("x")) << endl;
  return 0;
}

Common Lisp

Lisp benefits from the use of the built-in s-expression type:

(defun d (e x)
  (cond
   ((atom e) (if (eq e x) 1 0))
   ((eq (car e) '+) `(+ ,(d (cadr e) x) ,(d (caddr e) x)))
   ((eq (car e) '*) `(+ (* ,(cadr e) ,(d (caddr e) x))
                        (* ,(caddr e) ,(d (cadr e) x))))))

(defvar *e* '(+ (+ (* a (* x x)) (* b x)) c))

(d *e* 'x)

The result is printed as:

(+ (+ (+ (* A (+ (* X 1) (* X 1))) (* (* X X) 0)) (+ (* B 1) (* X 0))) 0)

F#

In F#, the + and * operators can be overloaded to work with the user-defined expr type:

type expr =
  | Int of int
  | Add of expr * expr
  | Mul of expr * expr
  | Var of string with
    static member ( + ) (f, g) = Add(f, g)
    static member ( * ) (f, g) = Mul(f, g)
  end

let rec d e x = match e with
  | Int n -> Int 0
  | Add(f, g) -> d f x + d g x
  | Mul(f, g) -> f * d g x + g * d f x
  | Var v -> Int (if v=x then 1 else 0)

let rec string_of = function
  | Int n -> string_of_int n
  | Var v -> v
  | Add(f, g) -> "("^string_of f^" + "^string_of g^")"
  | Mul(f, g) -> "("^string_of f^" * "^string_of g^")"

let x = Var "x" and a = Var "a" and b = Var "b" and c = Var "c"

let e = a * x * x + b * x + c

let () = Printf.printf "d %s x = %s\n" (string_of e) (string_of (d e "x"))

OCaml

Note that this implementation performs simple simplifications as expressions are constructed and pretty prints expressions with minimal bracketing (only sums inside products are bracketed).

let ( +: ) f g = match f, g with
  | `Int n, `Int m -> `Int (n + m)
  | `Int 0, f | f, `Int 0 -> f
  | f, g -> `Add(f, g)

let ( *: ) f g = match f, g with
  | `Int n, `Int m -> `Int (n * m)
  | `Int 0, _ | _, `Int 0 -> `Int 0
  | `Int 1, f | f, `Int 1 -> f
  | f, g -> `Mul(f, g)

let rec d e x = match e with
  | `Int n -> `Int 0
  | `Add(f, g) -> d f x +: d g x
  | `Mul(f, g) -> f *: d g x +: g *: d f x
  | `Var v -> `Int (if v=x then 1 else 0)

open Printf

let rec print ff = function
  | `Int n -> fprintf ff "%d" n
  | `Var v -> fprintf ff "%s" v
  | `Add(f, g) -> fprintf ff "%a + %a" print f print g
  | `Mul(f, g) -> fprintf ff "%a %a" product f product g
and product ff = function
  | `Add _ as expr -> fprintf ff "(%a)" print expr
  | expr -> print ff expr

let x = `Var "x" and a = `Var "a" and b = `Var "b" and c = `Var "c"

let e = a *: x *: x +: b *: x +: c

let () = Printf.printf "d (%a) x = %a\n" print e print (d e "x")

The result is printed as:

d (a x x + b x + c) x = a x + x a + b