3
$\begingroup$

In the following, why does N not produce the expected decimal output, while Round does?

Cases[{ArcSec[-(3/Sqrt[5])]}, ArcSec[a_] -> {a, 2 a, N[a], Round[a,.01]}]

{{-(3/Sqrt[5]), -(6/Sqrt[5]), -(3/Sqrt[5]), -1.34}}
$\endgroup$
4
  • $\begingroup$ use RuleDelayed (:>) instead of Rule (->)? $\endgroup$
    – kglr
    Commented Sep 10, 2018 at 6:03
  • $\begingroup$ with Rule N[a] is evaluated to a before the value of a gets injected: inspect Cases[{ArcSec[-(3/Sqrt[5])]}, ArcSec[a_] -> N[a]] // Trace // Column $\endgroup$
    – kglr
    Commented Sep 10, 2018 at 6:16
  • $\begingroup$ Thank you, kglr! That is most helpful. Please turn that into an answer, because I think that really explains a lot. $\endgroup$ Commented Sep 10, 2018 at 6:49
  • $\begingroup$ @Raplh, posted the comment as an answer. $\endgroup$
    – kglr
    Commented Sep 10, 2018 at 7:04

1 Answer 1

3
$\begingroup$

Using RuleDelayed (:>) instead of Rule (->) gives the desired result:

Cases[{ArcSec[-(3/Sqrt[5])]}, ArcSec[a_] :> {a, 2 a, N[a], Round[a, .01]}]

{{-(3/Sqrt[5]), -(6/Sqrt[5]), -1.3416407864998738, -1.34}}

From RuleDelayed >> Properties and Relations:

  • -> evaluates when it is first entered; :> when it is used

With Rule the right-hand-side N[a] is evaluated to a before replacement occurs:

ArcSec[a_] -> N[a]

ArcSec[a_] -> a

ArcSec[a_] :> N[a]

ArcSec[a_] :> N[a]

Compare the Traces of the two cases:

Cases[{ArcSec[-(3/Sqrt[5])]}, ArcSec[a_] -> N[a]] // Trace // Column

enter image description here

Cases[{ArcSec[-(3/Sqrt[5])]}, ArcSec[a_] :> N[a]] // Trace // Column

enter image description here

For Round, both Rule and RuleDelayed give the same result, because Round[foo, .1] does not evaluate for non-numeric input foo (it "evaluates" to Round[foo, .1]) whereas N[foo] evaluates to foo.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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