when i do 1/2 in python why does it give me zero?.. even if i coerce it with float(1/2) still i get zero .. why??.. and how can i get around it??..
when i give arctan(1/2) i get 0 as answer.. but when i give arctan(.5) i get correct ans !!
when i do 1/2 in python why does it give me zero?.. even if i coerce it with float(1/2) still i get zero .. why??.. and how can i get around it??..
when i give arctan(1/2) i get 0 as answer.. but when i give arctan(.5) i get correct ans !!
float(1)/float(2)
If you divide int / int you get an int, so float(0) still gives you 0.0
atan(float(1)/2)
If you do:
atan(float(1/2))
in Python 2.x, but without:
from __future__ import division
the 1/2 is evaluated first as 0, then 0 is converted to a float, then atan(0.0) is called. This changes in Python 3, which uses float division by default even for integers. The short portable solution is what I first gave.
From the standard:
The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the ‘floor’ function applied to the result.
because python 2.x uses integer division for integers, so:
1/2 == 0
evaluates to True.
you want to do:
1.0/2
or do a
from __future__ import division
As these answers are implying, 1/2 doesn't return what you are expecting. It returns zero, because 1 and 2 are integers (integer division causes numbers to round down). Python 3 changes this behavior, by the way.
Your coercing doesn't stand a chance because the answer is already zero before you hand it to float.
Try 1./2
In Python, dividing integers yields an integer -- 0 in this case.
There are two possible solutions. One is to force them into floats: 1/2. (note the trailing dot) or float(1)/2.
Another is to use "from future import division" at the top of your code, and use the behavior you need.
python -c 'from future import division;import math;print math.atan(1/2)' yields the correct 0.463647609001
If 1/2 == 0 then float(1/2) will be 0.0. If you coerce it to float after it's been truncated it'll still be truncated.
There are a few options:
from __future__ import division
. This will make the / operator divide "correctly" in that module. You can use // if you need truncating division.float(1)/2
1.0/2
or 1/2.0
or 1.0/2.0
First, 1/2
is integer division. Until Python 3.0.
>>> 1/2
0
>>> 1.0/2.0
0.5
>>>
Second, use math.atan2
for this kind of thing.
>>> math.atan2(1,2)
0.46364760900080609
>>> math.atan(.5)
0.46364760900080609