Convert float to long python

I have a fac(n) function that returns n! , and I compare it with the gamut (n + 1)

 >>> from math import gamma >>> gamma(101)-fac(100) 0.0 >>> math.floor(gamma(101))-fac(100) 0.0 >>> long(gamma(101))-fac(100) -1716052534060312817912314997891197522637580074354635372754659484313875350886868191008427848256820699487696649234627144617147818134104040275968L 

gamma (101) = 100! and is an integer.

why are the results different?

+4
source share
2 answers

The results differ because of the limited precision of the floating-point type and because of the way the subtraction operator arranges its operands of the same type. The gamma function returns a float, so it cannot return an exact answer for numbers larger. This page gives a good description of the problems.

In gamma(101)-fac(100) term fac(100) converted to a float before the subtraction operation.

 >>> gamma(101) 9.332621544394415e+157 >>> float(fac(100)) 9.332621544394415e+157 

The most significant part of fac(100) , which corresponds to the float, corresponds to the value of gamma(101) , therefore, subtraction leads to 0.0 .

For your second test, gamma(101) has no fraction, so math.floor has no effect:

 >>> math.floor(gamma(101)) == gamma(101) True 

When you convert gamma(101) to long, you can clearly see that this is inaccurate:

 >>> long(gamma(101)) 933262154439441509656467047959538825784009703731840988 310128895405822272385704312950661130892883272778258496 64006524270554535976289719382852181865895959724032L >>> fac(100) 933262154439441526816992388562667004907159682643816214 685929638952175999932299156089414639761565182862536979 20827223758251185210916864000000000000000000000000L 
+6
source

Floating-point numbers do not have infinite precision, and converting them to long will not give absolutely accurate results. The difference you see is the difference between the gamma(101) floating-point representation and its actual integer value.

+2
source