[Tutor] Abs

Alan Gauld alan.gauld at btinternet.com
Mon Jul 27 10:43:30 CEST 2015


On 27/07/15 02:06, Job wrote:
> I want to be able to ask a user to input an integer and print out the root and power of the given integer.
>
> Why do you use abs(x) for this program?

You don't need to, and I'm not sure why you think you do?
I assume it says something about it in your assignment
description?

abs() converts a number to a positive so you could use
it as a guard to prevent you from taking the square root
of a negative number.

> So If I understand how and why abs() is used to find
 > the cube root of a perfect cube

In Python 2 the pow() function (and ** operator) refuse
to take fractional powers of negative numbers. So even
though you should be able to do:

 >>> pow (-8,0.33333)

you can't. You need to convert the number to positive which
is where abs comes in.

Note:
In Python v3 pow() function (and the ** operator) happily
take negative numbers. But it will tell you the root of
a negative number as a complex number result.
And abs() will convert a complex number into its magnitude
so that's a second option. if using Python 3.

In both cases you will need to manage the sign of the
final answer yourself since the use of abs() will always
convert things to a positive.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list