0

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?

GambitSquared
  • 2,311
  • 15
  • 23

1 Answers1

3

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.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257