A pretty dumb newbie question

Gerhard =?unknown-8bit?Q?H=E4ring?= gh_pythonlist at gmx.de
Mon Dec 3 21:51:53 EST 2001


On Tue, Dec 04, 2001 at 02:24:12AM +0000, N64fan2017 wrote:
> How would you calculate square root? I've tried
> x**1/2
> Which doesn't work

As already proposed, you can use the sqrt function from the math module.

The real problem you're experiencing is that almost all programming
languages won't give you a floating point number from the expression 1/2
but an integer instead. You'll get a floating point number when at least
one of the numbers involved is a floating point number, so:

    1.0/2   1/2.0    1.0/2.0

will all return the floating point number 0.5.

Beware that on a computer, some floating point numbers aren't accurate.
So, generally, don't compare floating point numbers with ==. The Python
FAQ has an entry on floating point numbers.

One other issue you touched is operator precendence. This is another
reason why x**1/2 won't work as expected: the "**" operator has higher
precendence than the "/" operator. So you'd have to use brackets, like
in 2**(1.0/2).

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))




More information about the Python-list mailing list