Ask Your Question
1

'TypeError: unable to coerce to a real number' when trying to plot the real component of sqrt(z)

asked 2022-06-14 15:08:45 +0100

Ammardian gravatar image

Recently I have been trying to find a way to visualise complex functions and have been using sage to automate the process, by viewing the x and y axes as Re(z) and Im(z), and the z-axis as either Re(f(z)) or Im(f(z)). I have had success plotting some complex functions, but am finding now that sqrt(z) for example, will not plot, and produces this TypeError. The code I have used to try plot the function Re(sqrt(z)) is below,

x, y, z = var('x, y, z')
z1, z2 = -1, 1
ni = 10*(z2-z1)
dz = (z2-z1)/ni
def col3(x,y,z):
  return float(0.5*dz + floor((z-z1)/dz)/ni)  
surf = implicit_plot3d(z==real_part(sqrt(x+I*y), (x,-2,2), (y,-2,2), (z,-1,1), color=(col3, colormaps.jet))
show(surf, aspect_ratio[1,1,2])

I suspect the cause of the error is found in the fact that when sage calculates Re(sqrt(z)), it produces the following:sqrt(abs(x+I*y))*cos(1/2*arctan2(y, x)). Therefore I suspect that because it doesn't seem to know that abs(x+I*y) = sqrt(x^2+y^2), it assumes that the number is still complex and throws the error. So, I am wondering if there is a way for me to get sage to produce sqrt(sqrt(x^2+y^2))*cos(1/2*arctan2(y, x)) instead when I find Re(sqrt(z)) so that I can plot it.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-06-15 06:59:35 +0100

slelievre gravatar image

updated 2022-06-16 09:15:08 +0100

Try declaring the variables as real.

This is done using domain='real'.

That seems to help in this case, see the result below.

sage: x, y, z = SR.var('x, y, z', domain='real')
sage: assumptions()
[x is real, y is real, z is real]
sage: z1, z2 = -1, 1
sage: ni = 10*(z2 - z1)
sage: dz = (z2 - z1)/ni
sage: def col3(x, y, z):
....:     return float(0.5*dz + floor((z - z1)/dz)/ni)
sage: f = z-real(sqrt(x + I*y))
sage: xx, yy, zz = (x, -2, 2), (y, -2, 2), (z, -1, 1)
sage: cc = (col3, colormaps.jet)
sage: surf = implicit_plot3d(f, xx, yy, zz, color=cc)
sage: surf.show(aspect_ratio=(1, 1, 2))
Launched html viewer for Graphics3d Object

SageMath implicit 3D plot with colormap

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: 2022-06-14 15:08:45 +0100

Seen: 214 times

Last updated: Jun 16 '22