-3

My question is why does,

import math
a = math.sqrt(3)
area = a * (1 / 2)
print area

give an output of 0.0, but,

import math
a = math.sqrt(3)
area = a / 2
print area

give an output of 0.866025403784

Matthias
  • 12,873
  • 6
  • 42
  • 48

2 Answers2

0

Actually this is a problem of integer truncation in 2.X.

X / Y Classic and true division. In Python 2.X, this operator performs classic division, truncating results for integers, and keeping remainders (i.e., fractional parts) for floating-point numbers. In 2.X, the / does classic division, performing truncating integer division if both operands are integers and float division (keeping remainders) otherwise.

In Python 3.X, it performs true division, always keeping remainders in floating-point results, regardless of types. In 3.X, the / now always performs true division, returning a float result that includes any remainder, regardless of operand types.

In Python 2.X You can "fix" this by adding from __future__ import division to your script. This will always perform a float division when using the / operator and use // for integer division.

But you can make at least one of the operands in the division is a float, you'll get a float result.

>>> from __future__ import division

area=a*(1/2) area 0.8660254037844386

I hope this will help you.

varshneydevansh
  • 101
  • 1
  • 4
-1

i think you are using python 2.7 this is the problem with python 2.7 it evaluate 1/2 as zero because it think 1&&2 both as integer so it gives result as integer but in second case your math.sqrt() function return an double value so it gives result as double . but if you use python 3.0 the problem is fixed you get same result in both the cases you can try it it gives 1/2 as 0.5 .

H A G K
  • 1
  • 4