Message Boards Message Boards

Use procedural programming (Loops) in this case?

Posted 8 years ago

I know loops aren't the best choice in Mathematica, there's a lot of great built in functions to use, but there are times when procedural programming is necessary or just to do for a challenge. I've posted several previous questions utilizing loops but I still struggle using them.

I am attempting to create a loop that will find the biggest value for k so that the slope of f(x) at Sqrt[k] is greater than some arbitrary value, we can call it 5 in this case..

So here is what I have so far..This is the function along with a visualization of the function, not like I can visually see where this k value would be located but I enjoy visuals.

Clear[f, x, k, g, integer]
f[x_] := x^2 + k*x
Plot3D[f[x], {x, 0, 10}, {k, 0, 10}, ColorFunction -> "Rainbow"]

In addition, I was able to work out this problem without using a loop, but I am very curious how I could use procedural programming in this case.

g[k_] = D[f[x], x] /. x -> Sqrt[k]; 
integer := N[Solve[g[k] == 5, k]]
integer
= 2.10102

I would of course round this value to 3 because 2 would not satisfy the condition.

I probably have most of the code already here, I at least it could be used in the loop somewhere.

Does anyone have any pointers? I know loops aren't everyone's first choice.

POSTED BY: Brandon Davis
2 Replies
Posted 8 years ago

That's great Bill. I thank you for your assistance. I'm now going to attempt either a Do or For loop next.

I think my only point of confusion is the very last line of code. I know "While" doesn't have a default output so the Print command is necessary, just not fully sure with the syntax on the inside. I'll mess around with it.

Thanks again!

POSTED BY: Brandon Davis
Posted 8 years ago

Perhaps this will give you some ideas about one way to use a loop

f[x_] := x^2 + k*x;
g[k_] := D[f[x], x] /. x -> Sqrt[k];
k = 1;
While[g[k] < 6,
  k = k + 1;
  If[k > 10, Print["Something went wrong"]; Break[]]
  ];
Print["g[", k, "]=", g[k]]
POSTED BY: Bill Simpson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract