0

This example from Power Programming in Mathematica doesn't work for me anymore: the values used for rootfinding are not printed during evaluation. What changed? Is there a new way to reproduce the old behavior? enter image description here

Michael E2
  • 235,386
  • 17
  • 334
  • 747
Diffycue
  • 1,834
  • 8
  • 11
  • 2
    As shown in the documentation, FindRoot[Sin[x] - Cos[x], {x, 0.5}, EvaluationMonitor :> Print["x = ", x]] – Bob Hanlon Mar 03 '23 at 00:04

1 Answers1

2

It's not Print but FindRoot that has changed its behavior. FindRoot now evaluates its argument symbolically and uses the result to find the root, instead of the original argument. Here are a few ways to reproduce the output in the book, except for the initial x:

FindRoot[Print[x]; Cos[x] - Sin[x],
 {x, 0.5},
 Evaluated -> False, Jacobian -> {{-Cos[x] - Sin[x]}}]
(*
0.5
0.793408
0.785398
0.785398

{x -> 0.785398} *)

obj // ClearAll; obj[x_?NumericQ] := (Print[x]; Cos[x] - Sin[x]); obj /: obj' = -Sin[#] - Cos[#] &; FindRoot[obj[x], {x, 0.5}] (* 0.5 0.793408 0.785398 0.785398

{x -> 0.785398} *)

FindRoot[ If[x [Element] Reals, Print[x]; Cos[x] - Sin[x]], {x, 0.5}, Jacobian -> {{-Cos[x] - Sin[x]}}] (* 0.5 0.793408 0.785398 0.785398

{x -> 0.785398} *)

You need to provide the derivative so the FindRoot will use the same method as in the book (Newton's with a symbolic Jacobian/derivative). The goal in the examples above is to supply an argument that when evaluated symbolically, it doesn't evaluate to a Print-less expression. Note Evaluated -> False, which suppress evaluation of the argument, also prevents the automatic construction of the Jacobian; hence the Jacobian option.

I'm pretty sure this goes back a ways, well before (as the question is currently tagged).

Michael E2
  • 235,386
  • 17
  • 334
  • 747
  • You can add a def, obj[x_] := Null /; (Print[x]; False); to the second example if you'd really like to see the x. :) – Michael E2 Mar 03 '23 at 01:28