0
$\begingroup$

I have created this code:

xn = {4, -4, 4, -4}
f[x_] = Piecewise[{{Sqrt[x], x >= 0}, {Sqrt[-x], x < 0}}]
f[xn]

With this code I would expect as a result:

{2,2,2,2}

But that's not what I get.

Question 1 - Why don't I get the desired result?

Question 2 - How to get the desired result?

$\endgroup$
  • 1
    $\begingroup$ f/@xn or SetAttributes[f, Listable]... $\endgroup$ – ciao Jul 12 '16 at 21:09
  • $\begingroup$ What is the difference between f/@xn and f[xn]? $\endgroup$ – GambitSquared Jul 12 '16 at 21:10
  • $\begingroup$ Why not use Sqrt[Abs[x]]? $\endgroup$ – J. M. will be back soon Jul 12 '16 at 21:11
  • $\begingroup$ "What's the difference" - in your notebook, highlight the /@ and press F1, so that you can answer your own question. $\endgroup$ – J. M. will be back soon Jul 12 '16 at 21:11
  • 2
    $\begingroup$ Well, you didn't say that you were going to differentiate the blasted thing… $\endgroup$ – J. M. will be back soon Jul 12 '16 at 21:58
3
$\begingroup$

Your code shows two elementary misunderstandings. First, you do not understand the difference between Set and SetDelayed. Second, you do not understand what a Listable function is. Yet both these concepts are fundamental to working with Mathematica.

An experienced Mathematica user would write your code as

xn = {4, -4, 4, -4};
f[x_] := Piecewise[{{Sqrt[x], x >= 0}, {Sqrt[-x], x < 0}}]
f /@ xn

without even having to think about it.

$\endgroup$

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