First time here? Check out the FAQ!

Ask Your Question
1

numpy cube root 'not callable'

asked 3 years ago

Abbas Jaffary gravatar image

I would like to plot the numpy.cbrt function in Sage.

The example:

import numpy as np
parametric_plot([u,np.sin(u)], (u,0,pi))

plots a sine wave, but

parametric_plot([u,np.cbrt(u)], (u,0,pi))

produces the error:

TypeError: loop of ufunc does not support argument 0 of type sage.symbolic.expression.Expression which has no callable cbrt method

Isn't Sage passing the interval [0,pi] as an array when constructing the plot? I'd like to know why some numpy functions will work in this manner with Sage, and why others do not, and if there is a workaround.

FWIW:
I am doing this to test numpy numerical precision vs. Sage built-in math functions. Numpy seems to be more precise, even using Sage RealField precision beyond 53 bits.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
1

answered 3 years ago

slelievre gravatar image

Some functions in Sage or NumPy do not support symbolic arguments.

Plotting using such functions requires using them as callable functions.

The reference manual should insist on that...

(Currently, most if not all examples in the documentation use symbolic expressions.)

Here we use the NumPy functions in the question:

sage: import numpy as np

sage: parametric_plot([lambda u: u, np.sin], (0, pi))
Launched png viewer for Graphics object consisting of 1 graphics primitive

sage: parametric_plot([lambda u: u, np.cbrt], (0, pi))
Launched png viewer for Graphics object consisting of 1 graphics primitive

Here we use equivalent functions provided by SageMath:

sage: parametric_plot([lambda u: u, sin], (0, pi))
Launched png viewer for Graphics object consisting of 1 graphics primitive

sage: parametric_plot([lambda u: u, lambda u: real_nth_root(u, 3)], (0, pi))
Launched png viewer for Graphics object consisting of 1 graphics primitive
Preview: (hide)
link

Comments

Thank you. Incidentally, real_nth_root is what I wanted to compare against np.cbrt:

x1 = cos(1).n()  # Sage/Python standard Cosine function at 1 radian
x2 = np.cos(1)  # Numpy Cosine function at 1 radian

negative_cube_root = real_nth_root(-1*x1,3)      
np_negative_cube_root = np.cbrt(-1*x2.item(0))

C = [negative_cube_root, np_negative_cube_root]

show(C)

[1.05281950345160,1.0528195034516041]

This minimal difference might propagate in a snag I had in another issue.

Abbas Jaffary gravatar imageAbbas Jaffary ( 3 years ago )

For certified error bounds use Arb via RealBallField and ComplexBallField.

slelievre gravatar imageslelievre ( 3 years ago )

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 3 years ago

Seen: 356 times

Last updated: Jun 30 '21