Just a note to point out that language can make difference. Lisp is particularly good for this problem.
(defun d (f x)
(etypecase f
(number 0)
(symbol (if (eq f x) 1 0))
(list (df (first f) (rest f) x))))
(defun df (op args x)
(let ((a (first args))
(b (second args)))
(case op
((+ -) `(,op ,(d a x) ,(d b x)))
(* `(+ (* ,a ,(d b x)) (* ,(d a x) ,b)))
(/ `(/ (- (* ,(d a x) ,b) (* ,a ,(d b x))) (^ ,b 2)))
(^ `(* (* ,b (^ ,a ,(1- b))) ,(d a x)))
(sin `(* (cos ,a) ,(d a x)))
(cos `(* (- (sin ,a)) ,(d a x))))))
Lisp likes prefix notation. This is equivalent to an abstract syntax tree for expressions. Binary operations look like (op lhs rhs)
. So to differentiate (3 sin(x^2))^2
,
> (d '(^ (* (sin (^ x 2)) 3) 2) 'x)
(* (* 2 (^ (* (SIN (^ X 2)) 3) 1))
(+ (* (SIN (^ X 2)) 0) (* (* (COS (^ X 2)) (* (* 2 (^ X 1)) 1)) 3)))
This is a correct answer, but clearly it's far from simple form. So the next step is to add an expression simplifier. With a very rudimentary one,
> (simplify (d '(^ (* (sin (^ x 2)) 3) 2) 'x))
(* (* 2 (* (SIN (^ X 2)) 3)) (* (* (COS (^ X 2)) (* 2 X)) 3))
With infix notation, this is 2(3 sin(x^2)) (3 cos(x^2) (2x))
. Obviously more simplification is possible, but getting to "most simple" by any useful definition is a complicated topic.