Ask Your Question
1

Graphing max function - unexpected behavior

asked 2018-09-30 14:22:00 -0500

leingang gravatar image

My minimal working example is:

(x,y) = var('x y')
def f(x,y):
    return max(abs(x),abs(y))

table([[f(x,y) for y in range(-3,4)] for x in range(-3,4)])

The output is this table:

  3   3   3   3   3   3   3
  3   2   2   2   2   2   3
  3   2   1   1   1   2   3
  3   2   1   0   1   2   3
  3   2   1   1   1   2   3
  3   2   2   2   2   2   3
  3   3   3   3   3   3   3

That looks like it ought to. But when I try

contour_plot(f(x,y),(x,-3,3),(y,-3,3))

I get something that looks a lot different. It seems I don't have enough karma to upload the image, but its looks more like the one that would be associated to this table:

table([[f(0,y) for y in range(-3,4)] for x in range(-3,4)])

  3   2   1   0   1   2   3
  3   2   1   0   1   2   3
  3   2   1   0   1   2   3
  3   2   1   0   1   2   3
  3   2   1   0   1   2   3
  3   2   1   0   1   2   3
  3   2   1   0   1   2   3

I have the issue isolated in a Sage worksheet on CoCalc. I don't have enough karma to include a link, either.

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
3

answered 2018-10-01 08:32:37 -0500

tmonteil gravatar image

The issue comes from the fact that the max(a,b) function is a Python builtin, that basically asks whether a<b and if not returns a. However, the symbolic expressions abs(x) and abs(y) are not comparable,

sage: bool(abs(x) < abs(y))
False
sage: bool(abs(x) > abs(y))
False

Hence, the max function will always return the first argument:

sage: max(abs(x),abs(y))
abs(x)
sage: max(abs(y),abs(x))
abs(y)

Here, you want to deal with the max wiewed as a symbolic expression, so you have to use max_symbolic instead:

sage: max_symbolic(abs(x),abs(y))
max(abs(x), abs(y))

sage: contour_plot(max_symbolic(abs(x),abs(y)),(x,-3,3),(y,-3,3))
edit flag offensive delete link more

Comments

Very informative, thank you.

leingang gravatar imageleingang ( 2018-10-02 11:38:27 -0500 )edit
1

answered 2018-09-30 14:25:03 -0500

leingang gravatar image

Using one of the related questions that came up after I submitted, I think I found the correct way to get the expected plot:

contour_plot(f,(x,-3,3),(y,-3,3))

However, this still doesn't work as expected:

contour_plot(max(abs(x),abs(y)),(x,-3,3),(y,-3,3))
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2018-09-30 14:22:00 -0500

Seen: 25 times

Last updated: Oct 01