[Tutor] How do I make Python calculate square roots?

Pierre Barbier de Reuille pierre.barbier at cirad.fr
Mon Jul 4 16:40:10 CEST 2005


Or, you can use:

complex(-1)**0.5

However the result is strange ...

>>> complex(-1)**0.5
(6.1230317691118863e-17+1j)

Pierre

Danny Yoo a écrit :
> 
> On Sat, 2 Jul 2005, Reed L. O'Brien wrote:
> 
> 
>>>    Does anyone know how to make Python calculate square roots?
>>>
>>
>>Raise to the 1/2 power.
>>
>>
>>>>>4**.5
>>
>>2.0
>>
>>>>>16**.5
>>
>>4.0
>>
>>>>>81**.5
>>
>>9.0
> 
> 
> 
> By the way, if you need to take the square roots of negative numbers, then
> the 'sqrt' function in the cmath module should do the trick:
> 
> ######
> 
>>>>(-1)**0.5
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: negative number cannot be raised to a fractional power
> 
>>>>import cmath
>>>>cmath.sqrt(-1)
> 
> 1j
> ######
> 
> 
> Best of wishes!
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68


More information about the Tutor mailing list