Message Boards Message Boards

0
|
6008 Views
|
4 Replies
|
0 Total Likes
View groups...
Share
Share this post:

How to code function whose value depends on conditions?

To be precise, I want to code in the function f(x,y) that gives 1/x if x = y + 1/2 and (-1/(1+x)) if x = y - 1/2 (no other pairs (x,y) satisfying neither will be considered). How?

POSTED BY: Ricardo Garcia
4 Replies
Posted 9 years ago

You can also define f separately for the two conditions by placing a constraint on the pattern matching. When neither constraint is met, f is undefined and so is returned unevaluated.

In[1]:= f[x_, y_] := 1/x /; x == y + 1/2

In[2]:= f[x_, y_] := -1/(1 + x) /; x == y - 1/2

In[4]:= f[1, 3/2]

Out[4]= -(1/2)

In[5]:= f[2, 3/2]

Out[5]= 1/2

In[6]:= f[1, 1]

Out[6]= f[1, 1]
POSTED BY: David Keith

Thank you!

POSTED BY: Ricardo Garcia
Posted 9 years ago

This should do it?

f[x_, y_] := 
 Which[x == y + 1/2, 1/x, x == y - 1/2, -1/(1 + x)(*,True,0*)]
{f[1, 3/2], f[2, 3/2], f[6, 3/2]}

{-1/2, 1/2, Null}
POSTED BY: Erik Mahieu

Perfect, thanks a lot!

POSTED BY: Ricardo Garcia
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract