I was given the following problem:

Consider the equation x = exp(-x2). Plot the two curves on the same plot to get a rough idea of the intersection point. Then use a built - in function (e.g. FindRoot or FixedPoint or Solve) to find the solution to 100 significant digits and use the option "EvaluationMonitor" to find out how many iterations Mathematica took.

I was able to solve it except for the number of iterations it took to solve it.

  1. Why isn't it giving me the number of iterations it took to solve it?
  2. How do I fix it?

The following is my input and output:

In[42]:= f = x
g = Exp[-x^2]
Block[{c = 0}, {FindRoot[f == g, {x, 0, 1}, WorkingPrecision -> 100, 
   EvaluationMonitor -> c++], c}]

Out[42]= x

Out[43]= E^-x^2

Out[44]= {{x -> 
50472761980389255118225716068055969}, 1}

You need to use :> (RuleDelayed) not -> (Rule) for the monitors:

f = x;
g = Exp[-x^2];
Block[{steps = 0, funEval = 0, jacEval = 0, res},
 res = FindRoot[f == g, {x, 0, 1}, EvaluationMonitor :> funEval++, 
   StepMonitor :> steps++, 
   Jacobian -> {Automatic, EvaluationMonitor :> jacEval++}];
 Print["Function Evaluations: ", funEval];
 Print["Steps: ", steps];
 Print["Jacobian Evaluations: ", jacEval];

(* Function Evaluations: 8 Steps: 6 Jacobian Evaluations: 0

{x -> 0.652919} *)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.