cube roots in Sage

3,141 views
Skip to first unread message

gregory....@gmail.com

unread,
Jun 18, 2014, 2:34:25 AM6/18/14
to sage...@googlegroups.com
This has been brought up many times before, but I'd like to bring up
the possibility of adding two commands to Sage: cuberoot(x) and
nthroot(x, n)

The reason is that currently plot( x^(1/3), -5, 5) only shows values for x>0,
and not for x<0. The current work-around recommended is

plot(sign(x)*abs(x)^(1/3), -5, 5)
(Track ticket #11458)

which replaced the hideous

plot(lambda x: RR(x).nth_root(3), -5, 5, plot_points=20)

This is true in classes like Precalculus and Calculus 1, where trying to explain
workarounds like these would just really a headache for the instructor and
extremely fragile students.

Also the cube root can occur in many other situations and applications.
This is urgent, because my textbook "Sage for Undergraduates" is due
at the American Mathematical Society on June 30th.

The namespace is so huge, can't we just add two more commands?

I suggest:

def cuberoot(x):
    return sign(x)*((x*sign(x))^(1/3))

Last but not least, links to previous demands for exactly this problem:

https://www.mail-archive.com/sage-s...@googlegroups.com/msg11563.html
https://groups.google.com/forum/#!msg/sage-devel/_JeSMD-Kvfk/xeNstGrcvXQJ
https://groups.google.com/forum/#!topic/sage-support/icZ8ekC_P4Y
https://groups.google.com/forum/#!topic/sage-devel/_JeSMD-Kvfk
http://trac.sagemath.org/ticket/11458
https://sage.uwstout.edu/home/pub/32/
https://groups.google.com/forum/#!topic/sage-support/ZtRWScqMHMM
https://groups.google.com/forum/#!topic/sage-devel/_JeSMD-Kvfk

David Joyner

unread,
Jun 18, 2014, 7:11:40 AM6/18/14
to SAGE edu
On Wed, Jun 18, 2014 at 2:34 AM, <gregory....@gmail.com> wrote:
> This has been brought up many times before, but I'd like to bring up
> the possibility of adding two commands to Sage: cuberoot(x) and
> nthroot(x, n)
>


Just to be clear, if you defined nthroot in the obvious way, the code would
check for each evaluation if n is an integer, then if even or odd, right?
Wouldn't that slow down a plot compared to what you have below?
> --
> You received this message because you are subscribed to the Google Groups
> "sage-edu" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to sage-edu+u...@googlegroups.com.
> To post to this group, send email to sage...@googlegroups.com.
> Visit this group at http://groups.google.com/group/sage-edu.
> For more options, visit https://groups.google.com/d/optout.

William Stein

unread,
Jun 18, 2014, 9:55:37 AM6/18/14
to sage-edu

Is this only something that comes up for plotting? 

David Smith

unread,
Jun 18, 2014, 10:22:25 AM6/18/14
to sage...@googlegroups.com
No.  I just checked a definite integral interact in our calculus text.  It works fine to integrate x^(1/3) from 0 to 2, but when asked to integrate from -2 to 2, it returns the answer from 0 to 2.  It would be a great help to me to be able to tell students that cuberoot(x) is a legitimate function.

David Smith

unread,
Jun 18, 2014, 10:58:46 AM6/18/14
to sage...@googlegroups.com
Oops, sorry.  I forgot about the change that requires clicking "Submit" to change the interval.  When you try to integrate x^(1/3) from -2 to 2, you get the error message "negative number cannot be raised to a fractional power" -- which of course is false for some fractional powers.


On Wednesday, June 18, 2014 9:55:37 AM UTC-4, William Stein wrote:

kcrisman

unread,
Jun 18, 2014, 8:48:36 PM6/18/14
to sage...@googlegroups.com
Just to chime in, as someone who has dealt with this question a lot (though, perhaps ironically, never in a classroom situation):

I would be very against a "cuberoot" function, but an "nthroot" function where it was really clear what input was allowed could fly.  I appreciate Greg's rationale.  Note however - what is the 0.1 power? Is that the same as the 1/10 power?  This is a tricky floating point question to interpret. 

I don't think that the slowdown would be too bad since it would primarily be for pedagogical purposes for plotting.

David, I don't know how this would work with integrals, though - we'd have to see if Maxima had something equivalent.  Perhaps it could do a temporary set of the Maxima domain to real somehow, if that is what allows Maxima to do the "right thing" in this context, I don't know.

Thanks for fighting the good fight on trying to resolve this once and for all!
- kcrisman

David Smith

unread,
Jun 19, 2014, 12:39:26 PM6/19/14
to sage...@googlegroups.com
I could live with nthroot -- but is cuberoot (or curt or cbrt) so different from sqrt?  Anyway, it would be nice to have functions that resemble ones students see routinely without generating error messages.  I'm very much aware of the difficulties involved in reaching that goal, and I'll be patient. 

Still waiting for a solution on arcsec, as well.  There the issue is primarily plotting, although "integral" fails, even with a proper domain.  numerical_integral works as it should.

In the great scheme of things, these are certainly peripheral issues -- and they wouldn't be issues at all if textbook authors didn't feel obliged to drag in every function they know about.  As author, I'll guilty of that too (fear of the adoption committee), but in my defense, we only do these things in exercises.

Robert Bradshaw

unread,
Jun 19, 2014, 1:37:07 PM6/19/14
to sage...@googlegroups.com
On Thu, Jun 19, 2014 at 9:39 AM, David Smith <d...@math.duke.edu> wrote:
> I could live with nthroot -- but is cuberoot (or curt or cbrt) so different
> from sqrt?

Cubic roots are much less common. They don't even have their own
(unparameterized) symbol. I think some kind of a (real?) nth root
function makes sense.

> Anyway, it would be nice to have functions that resemble ones
> students see routinely without generating error messages. I'm very much
> aware of the difficulties involved in reaching that goal, and I'll be
> patient.
>
> Still waiting for a solution on arcsec, as well. There the issue is
> primarily plotting, although "integral" fails, even with a proper domain.
> numerical_integral works as it should.
>
> In the great scheme of things, these are certainly peripheral issues -- and
> they wouldn't be issues at all if textbook authors didn't feel obliged to
> drag in every function they know about. As author, I'll guilty of that too
> (fear of the adoption committee), but in my defense, we only do these things
> in exercises.

It might not hurt to include a script for your students to copy/import
that makes common definitions you want.

> On Wednesday, June 18, 2014 8:48:36 PM UTC-4, kcrisman wrote:
>>
>> Just to chime in, as someone who has dealt with this question a lot
>> (though, perhaps ironically, never in a classroom situation):
>>
>> I would be very against a "cuberoot" function, but an "nthroot" function
>> where it was really clear what input was allowed could fly. I appreciate
>> Greg's rationale. Note however - what is the 0.1 power? Is that the same as
>> the 1/10 power? This is a tricky floating point question to interpret.
>>
>> I don't think that the slowdown would be too bad since it would primarily
>> be for pedagogical purposes for plotting.
>>
>> David, I don't know how this would work with integrals, though - we'd have
>> to see if Maxima had something equivalent. Perhaps it could do a temporary
>> set of the Maxima domain to real somehow, if that is what allows Maxima to
>> do the "right thing" in this context, I don't know.
>>
>> Thanks for fighting the good fight on trying to resolve this once and for
>> all!
>> - kcrisman
>

Andrey Novoseltsev

unread,
Jun 19, 2014, 2:31:04 PM6/19/14
to sage...@googlegroups.com
I was mostly hurt by Sage/Maxima correctness when dealing with iterated integrals, that I wanted to compute step by step. After trying all kinds of assumptions derived from integral limits and assuming all rooted expressions positive, I use as a last resort FTC no matter what is the domain. For example, if you use
http://interact.math.ualberta.ca/MATH215/Three_iterated_integrals.html
and change the internal integral to -1..3 for 1/z integrand and check "Try to compute" on the bottom, it will work. If will show a red equality sign with a question mart to indicate that something may be wrong, but for teaching calculus I found it to be better than worrying about analytic functions and branch cuts. I believe that with these adjustments there were no examples that my applet couldn't do and WA could. Yet I certainly don't propose to have default integrate functions in Sage behave like this.

Perhaps something like "real_teaching_mode()" similar to "automatic_names()" would be handy, but implementing it may not be worth the effort...

Thank you,
Andrey

Martin Flashman

unread,
Jun 19, 2014, 11:35:50 PM6/19/14
to sage...@googlegroups.com
I join the call for at least an nth root function.

It is provided in GeoGebra by the function nroot(x,n) and in Winplot by root(n,x).
I don't know specifically how these are coded- but they appear to work with x a real variable and n a non-zero integer. and I'm not sure what how it interprets  n=0... but neither give an error message and GeoGebra seems to have nroot(x,0) = 0 for x in (-1,1).

GeoGebra gives a correct integral for nroot(x,3) from -8 to 27.
The processing efficiency for this function is not noticeable for a human like myself- and the advantage for use by students at pre-caculus and beginning calculus would be quite positive.

Sorry- but it is something that should be remedied if SAGE is to make itself attractive to less advanced users.

Just my $.02.
Martin Flashman

Gerald Smith

unread,
Jun 20, 2014, 3:47:30 PM6/20/14
to sage...@googlegroups.com
Guys, please keep in mind that exponentials of negative bases are not really functions.  They give a mix of real and multivalued complex results. You cannot treat  x^(1/3) as a synonym for cuberoot (x) if x,0. The latter is a well defined function and the former is not.  Perhaps this might be a good reason to introduce a new function cuberoot(x) and evaluate it (using for example Newton''s Formula). 
Cheers,
MathBear
P.S. If you let the independent variable be the exponent and have a negative base, then for any interval of x however short, the function will flip flop infinitely often between real and multivalued complex results. The output is completely discontinuous and very messy. Just try graphing it!  There is a good reason why exponential finctions of a real variable are restricted to positive bases.


--

michel paul

unread,
Jun 20, 2014, 6:36:12 PM6/20/14
to sage...@googlegroups.com
Alpha shows the domain of y = x^(1/3) to be non-negative. However, it shows the domain of y = cube root of x to be all reals.

Most high school texts present a cube root function whose domain is all reals. A few years ago this became an issue in an Alg 2 class. I was having the students find domains and ranges of functions, and a student pointed out that Alpha contradicted our text and wondered why. This turned into a discussion of 'what is the cube root of -1?' 

Both Google calc and GeoGebra evaluate (-1)^(1/3) as -1. Alpha gives the complex expression

Both Mathematica and Sage leave (-1)^(1/3) unevaluated unless you ask for the numeric approximation.

I find it interesting that Alpha and Mathematica give different evaluations for (-1)^(1/3). 

And then, Alpha evaluates cube root of -1 as -1!

Also note the different uses of the radical sign. In the cases of 'cube root' there's an extra little hook on the radical that is not present for '^(1/3)'.

This is very interesting. I think there are some issues here pertinent to our secondary curriculum. We tell the kids about the Fundamental Theorem of Algebra, but then as they go into Analysis and Calculus, we pretend it doesn't exist. All attention gets focused on the reals.

- Michel
--
===================================
"What I cannot create, I do not understand."

- Richard Feynman
===================================
"Computer science is the new mathematics."

- Dr. Christos Papadimitriou
===================================

Gregory Bard

unread,
Jun 20, 2014, 9:10:38 PM6/20/14
to sage...@googlegroups.com
(Note: I have a lot of cube-root related emails to reply to today. I
promise that I will get to everyone, eventually.)

The phenomenon which Michel Paul has spoken of is extremely
interesting. The way I would address the perplexed (or perhaps,
intrigued) student---provided that they know what complex numbers
are---is to say:

If I ask for the cube root of 8, there are three numbers z in the
complex plane such that z^3 = 8.
Specifically, they are
z = 2cos(0) + i2sin(0) = 2 + 0i = 2
z = 2cos(120) + i2sin(120) = -1 + i sqrt(3)
z = 2cos(240) + i2sin(240) = -1 - i sqrt(3)

However, of these three, the first is real, and so normally that's
"the one we want" (at least, usually.)

If I ask for the cube root of -8, there are three numbers z in the
complex plane such that z^3 = -8.
Specifically, they are
z = -2cos(0) - i2sin(0) = -2 - 0i = -2
z = -2cos(120) - i2sin(120) = 1 - i sqrt(3)
z = -2cos(240) - i2sin(240) = 1 + i sqrt(3)

Again, of these three, the first is real, and so normally that's "the
one we want" (at least, usually.)

Now it is noteworthy that I can get all three with solve( x^3 == 8, x
) or solve( x^3 == -8, x ).

However, I think asking nth_real_root( -8, 3 ) to return -2 is no more
exotic than asking nth_real_root( 8, 3 ) to return 2.

Does this make sense?
---Greg

p.s. I'm not sure how to address it with students who are not exposed
to the complex numbers yet. Perhaps I'd say, well...

(2)(2)(2) = 8 so we write cuberoot(8) = 2

(-2)(-2)(-2) = -8 so we write cuberoot(-8) = -2
> You received this message because you are subscribed to a topic in the
> Google Groups "sage-edu" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/sage-edu/0vGw_Pd6v_Y/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to

Gregory Bard

unread,
Jun 20, 2014, 9:21:04 PM6/20/14
to sage...@googlegroups.com
(Note: I have a lot of cube-root related emails to reply to today. I
promise that I will get to everyone, eventually.)

For Gerald Smith's point, I think we have to clarify between
nth_real_root( x, n ) having domain R x Z+ and range R (which I think
is okay) and the undesirable option of nth_real_root( x, n ) having
domain R x Q and range C (which I think is inadvisable).

If n is a positive integer, then there should be no ambiguity. (See my
response to Michel Paul if that's unclear.)

It is coherently conceivable to consider nth_real_root( x, n ) having
domain R x Q* where we could evaluate nth_real_root( x, p/q ) as (
nth_real_root( x, q ) )^p or equivalently ( nth_real_root( x^p, q ) ).
So long as q=/=0, we can use the odd/even status of q to figure out
how to handle the situation. However, as Gerald Smith so excellently
points out, in each neighborhood of any negative rational value of n,
no matter how small, there are some rational numbers with even
denominators and some rational numbers with odd denominators. Thus the
output would flip-flop between entirely real and entirely imaginary
numbers. I guess that's not mathematically forbidden but the word
"pathological" is perhaps not uncalled for.

Thoughts?
---Greg

On Fri, Jun 20, 2014 at 12:47 PM, 'Gerald Smith' via sage-edu
<sage...@googlegroups.com> wrote:
> You received this message because you are subscribed to a topic in the
> Google Groups "sage-edu" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/sage-edu/0vGw_Pd6v_Y/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to

Gregory Bard

unread,
Jun 20, 2014, 9:34:11 PM6/20/14
to sage...@googlegroups.com
It seems that the consensus on both Sage-devel and Sage-edu is to go
with some sort of nth_real_root function. I propose the following,
which I have tested for evaluation, plotting, differentiation, and
integration. Sadly, the derivative has a Dirac delta in it, which is
... perhaps unavoidable because of the vertical tangency of the
cuberoot function at x=0. (Naturally, we can remove the asserts once
testing is completed.
---Greg

def nth_real_root( x, n ):
"""Note: n must be a positive integer. However, x is any real number.
(Otherwise this explanation will make no sense.)
For odd values of n, we return the unique real number y such
that y^n = x.
For even values of n, if x<0, there is no real number y such
that y^n = x and so we throw an exception.
For even values of n, if x=>0, then we return the unique real
number y such that y^n = x."""

if ((n in ZZ)==false):
raise RuntimeError('nth_real_root(x,n) requires n to be a
positive integer. Your n is not an integer.')

if (n<=0):
raise RuntimeError('nth_real_root(x,n) requires n to be a
positive integer. Your n is not positive.')

assert (n in ZZ)
assert (n>0)

if ((n%2) == 0):
# n is even
if (x<0):
raise RuntimeError('There is no nth real root (of a
negative number x) when n is even.')
else:
return x^(1/n)

assert ((n%2)==1)
# n is odd
return sign(x)*(abs(x))^(1/n)

David Joyner

unread,
Jun 20, 2014, 9:35:42 PM6/20/14
to SAGE edu
On Fri, Jun 20, 2014 at 9:10 PM, Gregory Bard
<gregory....@gmail.com> wrote:
> (Note: I have a lot of cube-root related emails to reply to today. I
> promise that I will get to everyone, eventually.)
>

Thanks Greg. I think the summary is that some sort of real nth root
function is supported by developers (provided it is very clearly documented)
but cube_root maybe not. Nils Bruin has suggested code...


> The phenomenon which Michel Paul has spoken of is extremely
> interesting. The way I would address the perplexed (or perhaps,
> intrigued) student---provided that they know what complex numbers
> are---is to say:

...

Gerald Smith

unread,
Jun 24, 2014, 10:46:53 PM6/24/14
to sage...@googlegroups.com
A sneaky workaround that I have found works rather well when exponentials to a negative base appear in something you want to be a real valued function.   First factor out -1^n from your  -b^n expression: -b^n =  -1^n * b^n  and then let -1^n -=  cos(Pi*n) .  A bit of basic calculus will show that cos(Pi*n) =  the real part of -1^n and is always single valued and analytic,. 

^,..,^


> email to sage-edu+unsub...@googlegroups.com.

>
> To post to this group, send email to sage...@googlegroups.com.
> Visit this group at http://groups.google.com/group/sage-edu.
> For more options, visit https://groups.google.com/d/optout.
>
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "sage-edu" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/sage-edu/0vGw_Pd6v_Y/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to

> To post to this group, send email to sage...@googlegroups.com.
> Visit this group at http://groups.google.com/group/sage-edu.
> For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "sage-edu" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sage-edu+unsub...@googlegroups.com.

kcrisman

unread,
Jul 8, 2014, 10:30:09 PM7/8/14
to sage...@googlegroups.com
Ah, I missed all this.  Did you ever open a ticket (with this or Nils' or other code)?  I guess it's too late for your book (well, the 1st print edition, on the internet revision means something different, as a recent article I read on lit crit was pointing out...)
By the way, apparently it's better to use a try/except clause than an assert, so that we have a meaningful error message, or so I have heard, I'm not a PEP guru. 

David Smith

unread,
Jul 9, 2014, 11:49:19 AM7/9/14
to sage...@googlegroups.com
Does "you" mean me?  As best I can recall, the answer is no.  But it's never too late for our book -- even though it's "published" (and has been for 4 years), we're constantly making improvements, ranging from fixing typos to replacing interacts with prettier or more effective ones for the same tasks.  And when there is a cube root or nth root function that includes x<0 in the domain, we'll take advantage of that -- although it's not critical to our mission.  We haven't bothered with revision numbers (bad practice, I know), and "version" (which we're about to drop) refers to the technology required.  We have just posted our (final?) version, entirely Sage and MathJax based, no longer with any external CAS required.  You can see the result at calculuscourse.maa.org, where the only links are to Full Text and Sample Chapters.  The Sample is open to the public, while Full is behind a pay wall.  However, until next Monday, you can see the full text at calculuscourse.maa.org/main2/ -- and comments are welcome.  My sincere thanks to all who have helped us get up to speed on Sage interacts and responded to our requests for additional features.  DAS

gregory....@gmail.com

unread,
Jul 10, 2014, 6:20:51 PM7/10/14
to sage...@googlegroups.com
You are definitely correct about assert versus try/except. The assert is a debugging-stage tool, and once the code is fully debugged, some asserts will disappear and others will become try/catch, for the purpose of making a human-readable error message.

I did not open a ticket. I wanted to wait a few days for everyone to be able to say what they want and for a consensus to form. I think we have a consensus that we should do *something* but unless I am very much mistaken, the suggestion from Vincent Delecroix and Nils Bruin that we make a symbolic function has advantages. In fact, I think Nils Bruin has posted code to Sage-devel.

I have to confess that I don't understand Nils's code. Actually, I wasn't able to get the following to work, but I have a feeling that I am making a minor and stupid mistake with the syntax.

################
from sage.symbolic.function import SymbolicFunction
class nth_root(SymbolicFunction):
    def __init__(self):
        SymbolicFunction.__init__(self, 'nth_root', nargs=2)
    def _evalf_(self, n, x, parent=None):
        return parent(x).nth_root(n)

plot( nth_root( x, 3), -5, 5 )
################

Maybe someone here could explain exactly what the distinction is or what the pros/cons are for my approach versus Nils's? I have no idea.

I will also post this on Sage-Devel, but perhaps all future replies should be restricted to Sage-Devel and not Sage-Edu?
---Greg


On Tuesday, July 8, 2014 10:30:09 PM UTC-4, kcrisman wrote:

gregory....@gmail.com

unread,
Jul 10, 2014, 6:29:45 PM7/10/14
to sage...@googlegroups.com
I think kcrisman was referring to Sage for Undergraduates, my book, perhaps?. That's what sparked this original conversation about the plot of the cuberoot.

If people are curious, Sage for Undergraduates will be submitted any day now to the American Mathematical Society. It is long over due. The PDF copy will be free, and the printed book hopefully won't be too expensive. I do not plan to update the text "real time" with minor corrections over the months, (1) because I hope there aren't any errors, and (2) that's incompatible with my teaching load.

However, I do explain that command called real_nth_root is coming soon, that it will take care of this issue, and that it does not yet exist.

Moreover, this gave me a chance to praise the openness of open-source software versus corporate software. Open source software allows for these sorts of conversations leading to changes and upgrades.
---Greg

Norbert Domes

unread,
Jul 14, 2014, 4:13:55 PM7/14/14
to sage...@googlegroups.com
My suggestion for nth real root:



def nth_real_root(a,n):

    p = x^n - a
    L = p.roots(ring=RR,multiplicities=False)
    if L:
        return L[0]       # return L ?
    else:
        raise RuntimeError("no real root")

Martin Flashman

unread,
Jul 17, 2014, 1:29:41 PM7/17/14
to sage...@googlegroups.com
Norbert's solution is short but unfortunately for nth_real_root(4,2)
gives a result of -2 instead of what the TC MITS expected  result of 2.

One slight modification handles that issue to give results that match these expectations- Unfortunately- this function doesn't seem to plot!???:

def nth_real_root(a,n):

    p = x^n - a
    L = p.roots(ring=RR,
multiplicities=False)
    if L:
       return sgn(a)*sgn(L[0])*L[0] # return L ?

    else:
        raise RuntimeError("no real root")



ALSO-
On naming the function: eventually a shorter name would be helpful if this is to become a core real function:
perhaps  r_rootn(x,n) or simply rootn(x,n).

From a foggy morning in Arcata,
Martin Flashman

Dan Drake

unread,
Jul 17, 2014, 1:55:16 PM7/17/14
to sage...@googlegroups.com
On Thu, 17 Jul 2014 at 10:29AM -0700, Martin Flashman wrote:
> On naming the function: eventually a shorter name would be helpful if this
> is to become a core real function:
> perhaps r_rootn(x,n) or simply rootn(x,n).

I would argue that the longer name is more helpful. With "real_nth_root"
it's clear what you're getting; if I just say r_rootn or rootn, I might
wonder what the "r" and "n" meant. Anyone who wants something shorter
could do

rootn = real_nth_root

and use "rootn".

Dan

--
--- Dan Drake
----- www.math.wisc.edu/~ddrake/
-------
signature.asc

Norbert Domes

unread,
Jul 19, 2014, 3:18:07 AM7/19/14
to sage...@googlegroups.com
Provided L (the list of roots) is always in ascending order we could do: return L[-1]

But the main issue of my solution is:
it is too slow and even worse  it gulps so much memory that it fails

For example:

nth_real_root_2(4,2000)

Traceback (click to the left of this block for traceback)
...
MemoryError: Unable to allocate 4096000000 bytes memory for PARI.
Reply all
Reply to author
Forward
0 new messages