Help me with differential calculus!
Perl - 121 122
(+2 for -p
)
s/(?<![-\d.*^])-?[\d.]+(?![*^\d.])/0/g;s/(?<!\^)x(?!\^)/1/g;s/x\^(-?[\d.]+)/"$1*x^".($1-1)/ge;s/([\d.]+)\^x/ln($1)*$&/g
Test:
$ perl -p diff.pl << EOF
> -3
> 8.5
> x^0.5
> x^-7
> 0.5^x
> 7^x
> 3*x^5
> -0.1*0.3^x
> -5*x^2+10-3^x
> EOF
0
0
0.5*x^-0.5
-7*x^-8
ln(0.5)*0.5^x
ln(7)*7^x
3*5*x^4
-0.1*ln(0.3)*0.3^x
-5*2*x^1+0-ln(3)*3^x
Wolfram 136 134 109[Thanks to Calle for his comment below]
Limited support for product and chain rules.
n=n_?NumberQ;d[v_Plus]:=d/@v;d[v_]:=v/.{x_^n:>x^(n-1)d[x]n,n^x_:>Log[n]d[x]n^x,x_*y__:>d[x]y+d[y]x,n:>0,x:>1}
Example:
d[3^(x^2)*(x^3+2*x)^2]
>> 2*3^x^2*(2+3*x^2)*(2*x+x^3) + 2*3^x^2*x*(2*x+x^3)^2*Log[3]
Note that this does not use any "built-in functions to deal with equations or calculate derivatives": only pattern-matching is involved*.
[*Well... technically the interpreter also parses and builds a sort of AST from the input too]
Ungolfed:
d[expr_Plus] := d /@ expr;
d[expr_] := expr /. {
Power[x_, n_?NumberQ] :> n Power[x, n - 1] d[x],
Power[n_?NumberQ, x_] :> Log[n] Power[n, x] d[x],
Times[x_, y__] :> d[x] y + d[y] x,
n_?NumberQ :> 0,
x :> 1
}
Haskell 38 Chars
The function d
takes a function and returns a function. It is inputted in the form of a power series, and is outputted the same way (which is a type of whatever.)
d=zipWith(*)[1..].tail
For example, if we input x->x^2
, we get x->2*x
.
λ <Prelude>: d [0,0,1]
[0,2]
And for the exponential function.
λ <Prelude>: take 10 exp --exp redefined above to be in power series notation
[1.0,1.0,0.5,0.16666666666666666,4.1666666666666664e-2,8.333333333333333e-3,1.388888888888889e-3,1.984126984126984e-4,2.48015873015873e-5,2.7557319223985893e-6]
λ <Prelude>: let d=zipWith(*)[1..].tail in take 10 $ d exp
[1.0,1.0,0.5,0.16666666666666666,4.1666666666666664e-2,8.333333333333333e-3,1.388888888888889e-3,1.984126984126984e-4,2.48015873015873e-5,2.7557319223985893e-6]