# Creating a package on Mathematica which will use the first derivative test

This is what I have so far (I'm new at this sorry):

BeginPackage["FirstDerivativeTest"]
firstderivative[f_, x_] = Module[{df, sol, point, dfleft, dfright},

df:=D[f,x];
sol=Solve[df==0,x];
point={x,f}/.sol;

Do[
dfleft=df/.x->point-1;
dfright=df/.x->point+1;

If[dfleft<0 && dfright>0, type="local minimum"];
If[dfleft>0 && dfright<0, type="local maximum"];
Print[ "there is a ", type  , " at ",point ,"."],
{point,point}]]

EndPackage[]


It gives me the points, but it won't tell me if it is a local maximum or local minimum. If there are any tips on how to get this Print to work correctly it would be greatly appreciated.

• Isn't point a List? If so, what does dfleft<0 mean? Mar 29, 2017 at 15:46
• @anderstood note that he used point as both the list and the iteration variable. Sam, best practice would suggest you don't do that. Also I don't think you need a Print call there. You can use Table and it will return values. I think you'll be best served by going to the tutorial materials Wolfram has created. I'll post an answer walking through what I think you want, though. Mar 29, 2017 at 16:01

So there are a number of things here. First, find a good tutorial and read it. From the fact that you're using BeginPackage and Print statements I'm gonna guess you've used a different language before. Probably not python, either. Mathematica doesn't require that. We can just happily chug away in the front-end. (unless you're using Mathematica from the command-line, in which case you can just put this in a .m file).

Your question is really about, "how can I get Do to return values?", which has a very simple answer. Use Table. That's what it's built for.

So the code (plus tweaks) looks like this:

firstderivative[f_, x_] :=

Module[{df = D[f, x], point, dfleft, dfright},
point = x /. Solve[df == 0, x];
Table[
dfleft = df /. x -> p - 1;
dfright = df /. x -> p + 1;
Which[
dfleft < 0 && dfright > 0,
p -> "local minimum",
dfleft > 0 && dfright < 0,
p -> "local maximum",
True,
p -> "neither"
],
{p, point}]
]


Then test it on a simply poly:

In[115]:= firstderivative[x^2, x]

Out[115]= {0 -> "local minimum"}


Note that we sometimes find odd things:

In[116]:= firstderivative[Sin, x]

Out[116]= {x -> "neither"}


That's because Solve doesn't return numbers, here, but rather an expression:

In[119]:= Solve[Cos[x] == 0, x]

Out[119]= {{x ->
ConditionalExpression[-(\[Pi]/2) + 2 \[Pi] C[1],
C[1] \[Element] Integers]}, {x ->
ConditionalExpression[\[Pi]/2 + 2 \[Pi] C[1],
C[1] \[Element] Integers]}}
`

You'll have to get around that, but otherwise this should be fine.

• Thank you so much that was extremely helpful!
– sam
Mar 29, 2017 at 16:28
• @sam Always glad to help. Mar 29, 2017 at 16:29