1
$\begingroup$

I wrote a function which returns 1 if x^2 + y^2<=1:

f[x_, y_] := If[x^2 + y^2 <= 1, 1]

Now I'm trying to continue this function to take in multiple conditions like if x^2+y^2>1, |x|<=1 and |y|<=1, the function should return 0. I would also like to expand this function to take in 'or' statements such as if |x|>1 or |y|>1 then etc.

$\endgroup$
  • 1
    $\begingroup$ Look up Which, Switch, And and Or. $\endgroup$ – Szabolcs Feb 9 at 16:48
2
$\begingroup$

You can use rules in making your definitions, as follows

f[x_, y_] := 1 /; x^2 + y^2 <= 1
f[x_, y_] := 0 /; Abs[x] < 1 || Abs[y] < 1

giving the results that you request, and remaining unevaluated otherwise

{f[0.3, 0.4], f[0.9, 1.2], f[u, v]}
(* {1, 0, f[u, v]} *)

In general, Mathematica will apply the rules in the order you define them, but you can check this using DownValues[f]. (See documentation for more details).

|improve this answer|||||
$\endgroup$
  • 1
    $\begingroup$ No, in general Mathematica will apply the rules in the order from most specific to most general, unless no clear ordering is apparent and in which case the order of definition is used. $\endgroup$ – Roman Feb 9 at 18:43
  • 1
    $\begingroup$ Also, ?f gives more information than just DownValues. $\endgroup$ – Roman Feb 9 at 18:43

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.