-2

this is my code:

def pmi(w1,w2):
     x = float(1)
     x = (bg_fdist[(w1, w2)])/(f_brown[(w1)]*f_brown[(w2)])
     print x

the values entered will be:

>>> bg_fdist[('of','the')]
9781
>>> f_brown[('of')]
36412
>>> f_brown[('the')]
6997`

so i expect my x to be very small and between 0 and 1.

but i get as a return:

>>>> pmi('of','the')
0

i assume that might be, because x gets still handled as an integer? why is this? can anyone point out how i might get my expected result?

greetings!

bngschmnd
  • 111
  • 1
  • 10
  • 1
    You **replaced** the `float` object `x` was bound to with a new value. Python variables have no type, they are simply references to objects. – Martijn Pieters Dec 04 '14 at 14:56

2 Answers2

1

If you do

>>> x = float(1)
>>> x
1.0
>>> type(x)
<type 'float'>

x is indeed a float. But if after you instanciate it with an int, it's not a float anymore:

>>> x = 2
>>> x
2
>>> type(x)
<type 'int'>

When doing your division, you are using integer so:

>>> x = 2/4
>>> x
0
>>> type(x)
<type 'int'>

You still have an integer. Instead you could use float on your variable in your equation:

>>> x = float(2)/4
>>> x
0.5

You could also use from __future__ import division.

The current division (/) operator has an ambiguous meaning for numerical arguments: it returns the floor of the mathematical result of division if the arguments are ints or longs, but it returns a reasonable approximation of the division result if the arguments are floats or complex.

See: PEP 238

Community
  • 1
  • 1
fredtantini
  • 15,966
  • 8
  • 49
  • 55
1

The x that you have declared as float(1) has nothing whatsoever to do with the result of the calculation in the second line: it was simply thrown away and replaced with the result from there. Instead, you'll need to explicitly case some of the elements of that calculation to floats.

The whole thing could be made clearer by splitting it up, like this:

def pmi(w1,w2):
    first = float(bg_fdist[(w1, w2)])
    second = float(f_brown[(w1)]*f_brown[(w2)])
    result = first/second
    return result
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895